package com.dst.smart.service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import com.dst.smart.app.MyApplication;
import com.dst.smart.R;
import com.dst.smart.app.MainActivity;
import com.dst.smart.constant.Constants;
import com.dst.smart.dao.impl.IWidgetDAO;

import com.dst.smart.dao.impl.factory.DeviceFactory;
import com.dst.smart.dao.impl.factory.ModeFactory;
import com.dst.smart.dao.impl.factory.ModeListFactory;
import com.dst.smart.dao.impl.factory.RedInfraFactory;
import com.dst.smart.dao.impl.factory.RoomFactory;
import com.dst.smart.dao.impl.factory.SubscribeFactory;
import com.dst.smart.dao.impl.factory.VoiceFactory;
import com.dst.smart.json.AnHongUitils;
import com.dst.smart.json.ProjectUtils;
import com.dst.smart.json.SongUitils;
import com.dst.smart.json.WeatherUtils;
import com.dst.smart.model.BindProject;
import com.dst.smart.model.Room;
import com.dst.smart.model.Device;
import com.dst.smart.model.Mode;
import com.dst.smart.model.ModeList;
import com.dst.smart.model.RedInfra;
import com.dst.smart.model.RootPath;
import com.dst.smart.model.SubscribeInfo;
import com.dst.smart.model.VoiceInfo;
import com.dst.smart.model.WeatherInfo;
import com.dst.smart.music.MusicPlayMedia;
import com.dst.smart.player.entity.SongPlayInfo;
import com.dst.smart.socket.SocketClient;
import com.dst.smart.tools.AppTools;
import com.dst.smart.tools.HanziToPinyin;
import com.dst.smart.tools.HanziToPinyin.Token;
import com.dst.smart.tools.JSONHelper;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import static android.R.attr.host;
//import android.support.v4.media.session.MediaSessionCompat.Token;

public class SendCMD {
	// 唤醒播放音频
	/*
	 * private final static String[] WAKE_UP = {
	 * DemoConstant.XIAOAI_GREETING_EWZN, DemoConstant.XIAOAI_GREETING_GS,
	 * DemoConstant.XIAOAI_GREETING_SS, DemoConstant.XIAOAI_GREETING_WTZN };
	 */
	private static int type_window = 12;
	private static Map<String, String> map;
	//static StringBuffer sb = new StringBuffer();
	private static SendCMD install;
	//public static int wakeTime = 0;
	private int delayPrctime[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0 };
	private String[] setWords = new String[20];
	private static boolean setTimeRun = false;
	private static int loopIndex = 0;
	private static int SchloopIndex = 0;
	private static boolean oneSecond = false;
	private static boolean oneMinute = false;
	private String spaceNameStr = "";
	private static int nowSec = 0;
	private static int nowMin = 0;
	private String modecode = "00";
	private String modetime;
	private int ActionFlag;
	//private String mode = "0";
	private int randomKey = 0;
	private String deviceProductCode = "00";
	private String modeIo = "0";
	private String modeSthh = "00";
	private String modeStmm = "00";
	private String modeEndhh = "00";
	private String deviceIO = "0";
	private String modeEndmm = "00";
	private String modeMonth = "00";
	private String allControl="00";

	private String timeReturn="";
	//String deviceName;
	private String devieID = "";// 设备ID
	//public static int FreeBackPro = 0;
	private String words_ls = "";
	private int deviceValue;
	private int cStartPos;

	private String devieMid1 = "";
	private String devieMid2 = "";
	private String SendType = "";
	private String roomName = "";
	private static String PlayFreeBack = "";
	private long Prctime[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0 };
	private int PrcType[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0 };
	private String[] PrcWords = new String[20];

	private String[] EnableDate = new String[20];
	private String[] PrcSchWords = new String[20];
	private int PrcSchType[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0 };

	private int voiceInfoTime[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0 };
	private int voiceType[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0 };
	private String[] voiceInfoStr = new String[20];

	private String SubControlWords="";
	private int delaySubControl=0;

	private int bSearchFlag;
	//private String memDeviceName="";
	private int musicPlayPreSt=0;
	private Device deviceModelParam;
	public static synchronized SendCMD getInstance() {

		if (install == null) {
			install = new SendCMD();
			map = new HashMap<>();
			install.startTime();
		}
		return install;
	}

	public SendCMD() {
	}

	private void startTime() {
		new Thread(new Runnable() {

			public void run() {
				while (true) {
					try {
						//if (SendCMD.getInstance().datas.size() > 0) {
						//	if (!MainActivity.isTTS ) {
						//		MainActivity.playSound(4,
						//				SendCMD.getInstance().datas.remove(0));
						//	}
						//}
						// 獲取時間
						String ReturnStr = dateToString(
								new Date(System.currentTimeMillis()),
								"yyMMddHHmmss");
						int mGetVal = Integer.parseInt(ReturnStr.substring(10,
								12));
						if (nowSec != mGetVal) {
							nowSec = mGetVal;
							if (setTimeRun) {
								if (!oneSecond ) {
									oneSecond = true;
								}
							} else {
								String beijingTime = getWebsiteDatetime("http://www.beijing-time.org");
								if (beijingTime != null) {
									setTimeRun = true;
									RootPath rootPath= ProjectUtils.getRootPath();
									String city=rootPath.getCity();
									MainActivity.UploadText(city+"今天天气如何", 2,2);
									// MainActivity.playSound(1, "网路連結成功");
								}
							}
							mGetVal = Integer.parseInt(ReturnStr.substring(8,
									10));
							if (nowMin != mGetVal) {
								nowMin = mGetVal;
								// *t0017031910224901%03
								Calendar c = Calendar.getInstance();
								int mWay = Integer.parseInt(String.valueOf(c
										.get(Calendar.DAY_OF_WEEK)));
								sendSubCmd(203, "*t00" + ReturnStr + "0"
										+ (mWay - 1), null,0);
								if (setTimeRun) {
									if (!oneMinute) {
										oneMinute = true;
										Integer NowTime = Integer
												.valueOf(ReturnStr.substring(6,
														10));
										MainActivity.DoNotDisturb = !((NowTime > 600) && (NowTime < 2100));
										if(ProjectUtils.getRootPath().getIsVoiceAutoAdj() == 0) {
											switch (NowTime) {
												case 600:
													//case 700:
													//case 800:
												case 1400:
													MainActivity.activity.setVolum(15);
													break;
												case 1300:
												case 1200:
													MainActivity.activity.setVolum(10);
													break;
												case 1900:
													MainActivity.activity.setVolum(13);
													break;
												case 2000:
													MainActivity.activity.setVolum(11);
													break;
												case 2100:
													MainActivity.activity.setVolum(9);
												case 2200:
													MainActivity.activity.setVolum(7);
													break;
											}
										}
										// joe行程预约
										String date = AppTools.getDate();
										String time = AppTools.getTime();
										int week = AppTools.getWeekOfDate();
										SubscribeInfo info = SubscribeFactory
												.getSubscrite(date, week, time);
										if (info != null) {
											if(!info.getUserName().equals("1")) {//當enable使用
												String infoSubscribe = info.getSubscribeEvent()
														.replace("【", "[")
														.replace("】", "]");
												String[] ActMode={"[推送]","[远程]","[本地]","[语音]","[語音]","[静音]","[查询]","[查詢]"};
												int AlarmMode = 3;
												int cIndex;
												for(cIndex=0;cIndex<ActMode.length;cIndex++){
													if(infoSubscribe.contains(ActMode[cIndex])){
														infoSubscribe = infoSubscribe.replace(ActMode[cIndex], "");
														switch(cIndex){
															case 0:
															case 1:AlarmMode = 1;
																break;
															case 2:
															case 3:
															case 4:AlarmMode = 2;
																break;
															case 5:
															case 6:
															case 7:AlarmMode = 0;
																break;
														}
														break;
													}
												}
												if ((AlarmMode & 0x0001) > 0) {  //[推送]
													MainActivity.activity.addAnHong(infoSubscribe);
												}
												if ((AlarmMode & 0x0002) > 0) {  //[语音]
													MainActivity.preAlarmStr = MainActivity.preAlarmStr
															+ "提醒你" + infoSubscribe;
													MainActivity.preAlarmNum = 12;
												}
												if (info.getSubscribeAction()
														.length() > 0) {
													ReturnAct = "提醒你"
															+ info.getSubscribeEvent();
													voiceInfoAction(info
															.getSubscribeAction(), 0, 0);
												} else {
													MainActivity.playSound(
															5,
															"提醒你" + infoSubscribe);
												}
											}
										}
										if (!MainActivity.DoNotDisturb) {
											if ((nowMin %15) == 0) {
												RootPath rootPath= ProjectUtils.getRootPath();
												String city=rootPath.getCity();
												MainActivity.UploadText(city+"今天天气如何", 2,2);
												//MainActivity.UploadText("播放刘欢的歌曲",2);
											}
										}
									}
								}
							}
							if ((nowSec % 15) == 0) {
								if ((MainActivity.preAlarmNum > 0)
										&& (!MainActivity.isTTS )) {
									MainActivity.isTTS = true;
									MainActivity.playSound(5, "注意注意"
											+ MainActivity.preAlarmStr);
									MainActivity.preAlarmNum--;
									if (MainActivity.preAlarmNum == 0) {
										MainActivity.preAlarmStr = "";
									}
								}
							}
							if(delaySubControl>0) {
								delaySubControl--;
								if(delaySubControl==0) {
									sendSubCmd(0, SubControlWords, null,0);
								}
							}
							if(MainActivity.addSensorTime>0){
								MainActivity.addSensorTime--;
							}
						}
						if (setTimeRun && oneSecond) {
							if (delayPrctime[loopIndex] > 0) {
								delayPrctime[loopIndex]--;
								if (delayPrctime[loopIndex] == 0) {
									sendSubCmd(0, setWords[loopIndex], null,1); //1=不允許重複執行情景
									// setWords[loopIndex] = "";
								}
							}
							if (voiceInfoTime[loopIndex] > 0) {
								voiceInfoTime[loopIndex]--;
								if (voiceInfoTime[loopIndex] == 0) {
									if(voiceType[loopIndex]==0){
										sendSubCmd(0, voiceInfoStr[loopIndex], null,2); //2=不允許重複執行自問答
									}else if(voiceType[loopIndex]==1){
										MainActivity.UploadText(voiceInfoStr[loopIndex],1,2);
									}else if(voiceType[loopIndex]==2){  //播放[TTS歡迎光臨]
										MainActivity.playSound(4 , voiceInfoStr[loopIndex].replace("TTS","").trim());
									}else if(voiceType[loopIndex]==3){  //播放[ URL鏈接 ]
										//加上音樂練接地址
										//String URL="http://"+ProjectUtils.getRootPath().getServiceIP()+":99/File/Music/evening.mp3";
										String URL="http://"+ProjectUtils.getRootPath().getServiceIP()+":99/File/Music/"+voiceInfoStr[loopIndex].replace("URL","")+".mp3";
										MainActivity.playMusic(1,URL );
									}else if(voiceType[loopIndex]==4){  //播放[本地 SD鏈接音樂 ]
										//加上本地 SD音樂練接地址
										String URL=MyApplication.getInstance().getMusicDirectory(voiceInfoStr[loopIndex].replace("SD","").trim());
										if(URL.length()>0) {
											MainActivity.playMusic(1, URL);
										}
									}else if(voiceType[loopIndex]==5){
										sendSubCmd(0, voiceInfoStr[loopIndex].replace("ASK","").trim(), null,1); //1=允許執行自問答
									}else{
										MainActivity.activity.resetWakeup(false);
									}
									// voiceInfoStr[loopIndex] = "";
								}
							}
							if (Prctime[loopIndex] > 0) {
								Prctime[loopIndex]--;
								if (Prctime[loopIndex] == 0) {
									if (PrcType[loopIndex] == 0) { // device
										int dStart = -1;
										String[] ActionLink = { "同时", "并把",
												"然后" };
										for (String str : ActionLink) {
											dStart = PrcWords[loopIndex]
													.indexOf(str);
											if (dStart != -1) {
												break;
											}
										}
										if (dStart != -1) {
											MainActivity.preAlarmStr = MainActivity.preAlarmStr
													+ "提醒你"
													+ PrcWords[loopIndex]
													.substring(0,
															dStart);
											MainActivity.playSound(
													5,
													"提醒你"
															+ PrcWords[loopIndex]
															.substring(
																	0,
																	dStart));
											MainActivity.preAlarmNum = 12;
											sendSubCmd(0, PrcWords[loopIndex]
															.substring(dStart + 2),
													null,0);

											MainActivity.activity
													.addAnHong(MainActivity.preAlarmStr);
										} else {
											sendSubCmd(0, PrcWords[loopIndex],
													null,0);
										}
									} else {
										// 播放提示音
										MainActivity.preAlarmStr = MainActivity.preAlarmStr
												+ "提醒你" + PrcWords[loopIndex];
										MainActivity.playSound(5, "提醒你"
												+ PrcWords[loopIndex]);
										MainActivity.preAlarmNum = 12;
										MainActivity.activity
												.addAnHong(MainActivity.preAlarmStr);
									}
								}
							}
							loopIndex++;
							if (loopIndex >= 20) {
								loopIndex = 0;
								oneSecond = false;
							}
						}
						// oneMinute
						if (setTimeRun && oneMinute) {
							String nowTimeStr = ReturnStr.substring(0, 10);
							if ((EnableDate[SchloopIndex] != null)
									&& (EnableDate[SchloopIndex].length() >= 10)) {
								if (EnableDate[SchloopIndex].equals(nowTimeStr)) {
									if (PrcSchType[SchloopIndex] == 0) { // device
										int dStart = -1;
										String[] ActionLink = { "同时", "并把",
												"然后" };
										for (String str : ActionLink) {
											dStart = PrcSchWords[SchloopIndex]
													.indexOf(str);
											if (dStart != -1) {
												break;
											}
										}
										if (dStart != -1) {
											// 播放提示音
											MainActivity.preAlarmStr = MainActivity.preAlarmStr
													+ "提醒你"
													+ PrcSchWords[SchloopIndex]
													.substring(0,
															dStart);
											MainActivity.playSound(
													5,
													"提醒你"
															+ PrcSchWords[SchloopIndex]
															.substring(
																	0,
																	dStart));
											MainActivity.preAlarmNum = 12;
											sendSubCmd(
													0,
													PrcSchWords[SchloopIndex]
															.substring(dStart + 2),
													null,0);
											MainActivity.activity
													.addAnHong(MainActivity.preAlarmStr);
										} else {
											sendSubCmd(0,
													PrcSchWords[SchloopIndex],
													null,0);
										}
									} else {
										// 播放提示音
										MainActivity.preAlarmStr = MainActivity.preAlarmStr
												+ "提醒你"
												+ PrcSchWords[SchloopIndex];
										MainActivity.playSound(5, "提醒你"
												+ PrcSchWords[SchloopIndex]);
										MainActivity.preAlarmNum = 12;
										MainActivity.activity
												.addAnHong(MainActivity.preAlarmStr);
									}
									EnableDate[SchloopIndex] = "";
								}
							}
							SchloopIndex++;
							if (SchloopIndex >= 20) {
								SchloopIndex = 0;
								oneMinute = false;
							}
						}
						if (MainActivity.isAirbus > 0) {
							MainActivity.isAirbus--;
						}
						Thread.sleep(50);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	private String ReturnAct = "";
	private String deviceCmd = "";
	//private boolean isSendMode;
	private int MultiFlag;
	private boolean onlyPlaySound = false;
	//private boolean onlyPlayAnswer = false;

	public String sendCMD(int source, String netCmd, Device device) {
		if (netCmd.equals("") || (netCmd.length()==0)) {
			return "未知设备";
		}
		//if (MainActivity.isAirbus == 0) {
		//	onlyPlaySound = false;
		//onlyPlayAnswer = false;
		//}
		if ((source > 0) && (source < 128)) {
			String modeSthhTamp = "00";
			String modeStmmTamp = "00";
			String modeEndhhTamp = "00";
			String modeEndmmTamp = "00";
			List<Mode> modes = ModeFactory.getAll();

			for (int index = 0; index < modes.size(); index++) {
				Mode mode = modes.get(index);
				if (netCmd.contains(mode.getModeName())) {
					// 有识别词
					modecode = toHex(mode.getModeCode());
					modeIo = mode.getModeLoop() + "";
					if (source == 1) {
						// 获取空间集合
						List<ModeList> modeList = ModeListFactory.getModeDevice(mode.getId());
						if (modeList.size() > 0) {
							String[] startTime = mode.getStartTime().split(":");
							String[] endTime = mode.getEndTime().split(":");
							if (startTime.length > 1) {
								modeSthhTamp = startTime[0];
								modeStmmTamp = startTime[1];
							}
							if (endTime.length > 1) {
								modeEndhhTamp = endTime[0];
								modeEndmmTamp = endTime[1];
							}
							deviceCmd = "*M80" + modecode + "00" + modeIo
									+ "FFFF0000000000000000";
							TcpSender.sendMssageAF(2,deviceCmd);

							for (int j = 0; j < modeList.size(); j++) {
								ModeList deviceMode = modeList.get(j);
								String period = deviceMode.getModePeriod();
								int timepos1 = period.indexOf("--");
								String[] periodArr = new String[2];
								modeSthh=modeSthhTamp;
								modeStmm=modeStmmTamp;
								modeEndhh=modeEndhhTamp;
								modeEndmm=modeEndmmTamp;
								if (timepos1 > 0) {
									periodArr = period.split("--");
									String[] stareArr = periodArr[0].split(":");
									String[] endArr = periodArr[1].split(":");
									if (stareArr.length > 1) {
										if(Integer.parseInt(stareArr[0])!=Integer.parseInt(stareArr[1])){
											modeSthh=stareArr[0];
											modeStmm=stareArr[1];
										}
									}
									if (endArr.length > 1) {
										if(Integer.parseInt(endArr[0])!=Integer	.parseInt(endArr[1])){
											modeEndhh=endArr[0];
											modeEndmm=endArr[1];
										}
									}
								}
								modetime = "00";
								String delayed =AppTools.getNumbers(deviceMode.getModeDelayed().replace("秒",""));
								if (Integer.parseInt(delayed) > 0) {
									modetime = toHex(Integer
											.parseInt(delayed));
								}
								//String moth=deviceMode.getCreationTime();
								int startM=0;
								int endM=0;
								if(deviceMode.getBeginMonth().length()>0){
									startM=Integer.valueOf(deviceMode.getBeginMonth().substring(0, 1), 16);
								}
								if(deviceMode.getEndMonth().length()>0){
									endM=Integer.valueOf(deviceMode.getEndMonth().substring(0, 1), 16);
								}
								modeMonth=toHex((startM*16)+endM);

								//isSendMode = false;
								if (deviceMode.getDeviceTypeKey()==20) {
									boolean logicCmd=false;
									String[]  Logic={"设置在家安防","*C0019FA07FF0000EB010000","设置离家安防","*C0019FA07FF0000EC010000","设置睡眠安防","*C0019FA07FF0000ED010000","假如在家安防","*C0019FA07FF0000EB000000", "假如离家安防","*C0019FA07FF0000EC000000","假如睡眠安防","*C0019FA07FF0000ED000000","条件不成立","*C0019FA07FF0000EF000000","逻辑结束","*C0019FA07FF0000E0000000"
									};
									for (int i = 0; i < Logic.length; i+=2) {
										if (deviceMode.getModeFunction().contains(Logic[i])) {// 有识别词) {//有识别词
											sendMssageAF(source, Logic[i + 1]);
											logicCmd=true;
										}
									}
									if(logicCmd==false) {
										String AreStr = "";
										if (deviceMode.getModeFunction().equals("灯光全开") || deviceMode.getModeFunction().equals("灯光全关")
												|| deviceMode.getModeFunction().equals("设备全关") || deviceMode.getModeFunction().equals("设备全开")) {
											AreStr = "主页";
										}
										sendSubCmd(source,
												AreStr + deviceMode.getModeFunction(),
												null,0);
									}
								} else {
									String cmdStr=deviceMode.getRoomName()+deviceMode.getDeviceName()+deviceMode.getModeAction()+deviceMode.getModeFunction()+deviceMode.getModeTime();
									sendSubCmd(source, cmdStr, null,0);
								}
							}
						}
						// deviceCmd="*M04";
						deviceCmd = "*M04" + modecode + "00" + modeIo
								+ "FFFF0000000000000000";
						TcpSender.sendMssageAF(2,deviceCmd);
					}
					if (source == 2) {
						deviceCmd = "*M00" + modecode + "00" + modeIo
								+ "FFFF0000000000000000";
						TcpSender.sendMssageAF(2,deviceCmd);
					} else if (source == 3) {
						// deviceCmd="*M83";
						deviceCmd = "*M83" + modecode + "00" + modeIo
								+ "FFFF0000000000000000";
						TcpSender.sendMssageAF(2,deviceCmd);
					}
					deviceCmd = "*M85" + modecode + "00" + modeIo
							+ "FFFF0000000000000000";
					TcpSender.sendMssageAF(2,deviceCmd);
					break;
				}
			}
		} else {
			sendSubCmd(source, netCmd, device,0);
		}
		return ReturnAct;
	}

	// Device deviceModel;

	public void sendSubCmd(int modelflag, String netCmd, Device device,int repetition) { //repetition 防止模式重複執行
		int cEndPos;
		String CampStr;
		//Log.e("name", netCmd);
		if (netCmd.equals("") || netCmd == null) {
			return;
		}
		onlyPlaySound = false;
		ReturnAct = "";
		if (modelflag > 127) {
			if (device != null) {
				deviceProductCode = device.getProductsCode();
				deviceValue = Integer.parseInt(deviceProductCode, 16); // [self
				// HexToTen:deviceProductCode];
				deviceModelParam=device;
				devieID = device.getDeviceID();
				devieMid1 = "00";
				devieMid2 = "00";
				SendType = "AA";
				if (devieID.length() == 6) {
					devieID = device.getDeviceID().substring(0, 2);
					devieMid1 = device.getDeviceID().substring(2, 4);
					devieMid2 = device.getDeviceID().substring(4, 6);
				}
				deviceIO = "0";
				if (device.getDeviceIO().length() > 0) {
					deviceIO = device.getDeviceIO();
				}
			}
			String cmd;
			switch (modelflag) {
				case 255:
					// 发送获取设备状态指令
					GetDeviceState();
					break;
				case 254:
					// 设置內存數據
					break;
				case 253:
					// 获取內存數據
					break;
				case 252:
					// 设置互控
					break;
				case 250:
					words_ls = device.getDeviceName();
					checkPeriodForDeviceModel(device, 0, netCmd);
					break;
				case 249:
					// *T83000000 00 01 0B 25 000000000000
					cmd = "*T83000000" + devieMid1 + devieMid2 + deviceProductCode
							+ devieID + deviceIO + "00000000000";
					TcpSender.sendMssageAF(2,cmd);
					break;
				case 248:
					String array[] = netCmd.split(":");
					String Action;
					String Para;
					String event = array[3];
					int timeVal = timeComprartion(0, 0, event);
					Para = toHex(timeVal);
					if (event.contains("打开")) {
						if (timeVal > 0) {
							if (deviceValue == 5) { // IR 紅外線
								Action = "A1";
								Para = "01";
							} else if (deviceValue >= 48 && deviceValue <= 100) {// 空调&电视
								Action = "A8";
							} else if (deviceValue == type_window) { // windows
								Action = "50";
							} else {
								Action = "5" + deviceIO;
							}
						} else {
							if (deviceValue == 5) { // IR 紅外線
								Action = "A1";
								Para = "01";
							} else if (deviceValue >= 48 && deviceValue <= 100) {// 空调&电视
								Action = "A1";
								Para = "01";
							} else if (deviceValue == type_window) { // windows
								Action = "50";
								Para = "FF";
							} else {
								Action = "2" + deviceIO;
							}
						}
					} else {

						if (timeVal > 0) {
							if (deviceValue == 5) { // IR 紅外線
								Action = "A2";
								Para = "01";
							} else if (deviceValue >= 48 && deviceValue <= 100) {// 空调&电视
								Action = "A1";
								Para = "02";
							} else if (deviceValue == type_window) { // windows
								Action = "52";
							} else {
								Action = "6" + deviceIO;
							}
						} else {
							if (deviceValue == 5) { // IR 紅外線
								Action = "A2";
								Para = "01";
							} else if (deviceValue >= 48 && deviceValue <= 100) {// 空调&电视
								Action = "A1";
								Para = "02";
							} else if (deviceValue == type_window) { // windows
								Action = "52";
								Para = "FF";
							} else {
								Action = "1" + deviceIO;
							}
						}
					}
					// *T81 01 14 20 00 01 0B 25 20 00 00000000
					// T8180200320010642620500000000
					if (array[array.length - 1].equals("1")) {
						cmd = "*T81" + array[2] + array[0] + array[1] + devieMid1
								+ devieMid2 + deviceProductCode + devieID + Action
								+ Para + "00000000";
					} else {
						cmd = "*T00" + array[2] + array[0] + array[1] + devieMid1
								+ devieMid2 + deviceProductCode + devieID + Action
								+ Para + "00000000";
					}
					TcpSender.sendMssageAF(2,cmd);
					break;
				case 247:
					cmd = "";
					switch (Integer.parseInt(netCmd, 16)) {
						case 0:
							cmd = "*Z00" + toHex(device.getId() >> 8)
									+ toHex(device.getId() & 0x00FF)
									+ deviceProductCode + devieID + devieMid1
									+ devieMid2;
							break;
						case 1:
							cmd = "*Z01" + toHex(device.getId() >> 8)
									+ toHex(device.getId() & 0x00FF)
									+ deviceProductCode + devieID + devieMid1
									+ devieMid2;
							break;
						case 2:
							cmd = "*Z02000000000000";
							break;
						case 3:
							cmd = "*Z03000000000000";
							break;
						case 255:
							cmd = "*ZFF000000000000";
							break;
						default:
							break;
					}
					TcpSender.sendMssageAF(2,cmd);
					break;
				case 246: // 获取中继路由表
					String[] array1 = netCmd.split("_"); // [netCmd
					String Serial = toHex(Integer.parseInt(array1[1]));
					cmd = "";
					switch (Integer.parseInt(array1[0], 16)) {
						case 0: // delete one
							cmd = "*C001BAA" + Serial + toHex(device.getId() >> 8)
									+ toHex(device.getId() & 0x00FF) + "00"
									+ deviceProductCode + devieID + devieMid1
									+ devieMid2;
							break;
						case 1: // Add
							cmd = "*C001BAA" + Serial + toHex(device.getId() >> 8)
									+ toHex(device.getId() & 0x00FF) + "01"
									+ deviceProductCode + devieID + devieMid1
									+ devieMid2;
							break;
						case 2: // info
							cmd = "*C001BAA" + deviceProductCode + "00" + devieID
									+ "02" + Serial + "00" + devieMid1 + devieMid2;
							break;
						case 3:
							cmd = "*C001BAA" + Serial + toHex(device.getId() >> 8)
									+ toHex(device.getId() & 0x00FF) + "03"
									+ deviceProductCode + devieID + devieMid1
									+ devieMid2;
							break;
						case 255:// All delete
							cmd = "*C001BAA" + deviceProductCode + "00" + devieID
									+ "FF" + Serial + "00" + devieMid1 + devieMid2;
							break;
					}
					TcpSender.sendMssageAF(2,cmd);
					break;
				case 200:
					if(musicPlayPreSt!=Integer.parseInt(netCmd, 16)) {
						musicPlayPreSt=Integer.parseInt(netCmd, 16);
						if (musicPlayPreSt == 0) {
							// 音樂停止
							cmd = "*AW400";
							TcpSender.sendMssageAF(2,cmd);
							if (MainActivity.mIsWakeUp==255) {
								cmd = "*C0019F01E000000AA000000";
							} else {
								cmd = "*C0019F01E00000010000000";
							}
							TcpSender.sendMssageAF(2,cmd);
						} else {
							// 音樂播放
							cmd = "*AW401";
							TcpSender.sendMssageAF(2,cmd);
							if(MainActivity.sleepLight>0) {
								//final Random random = new Random();
								//cmd = "*C0019A0A30000AAAE0" + (random.nextInt(7) + 1) + "0000";
								cmd = "*C0019F01E000000E0" + MainActivity.sleepLight + "0000";
								TcpSender.sendMssageAF(2,cmd);
								MainActivity.sleepLight++;
								if(MainActivity.sleepLight>=8){
									MainActivity.sleepLight=1;
								}
							}
						}
					}
					break;
				case 201: // 喚醒
					TcpSender.sendMssageAF(2,netCmd);
					final Random random = new Random();
					// joe10 b0 f0 60 98 80 c0 98
					if (MainActivity.mIsWakeUp > 0) {
						cmd = "*C0019F01E000000A0" + toHex(random.nextInt(255)) + "0000";
					} else {
						/*
						 * // 随机播放提示音 TonePlayer.playTone(MainActivity.activity,
						 * WAKE_UP[random.nextInt(4)]);
						 */
						// 白光
						cmd = "*C0019F01E000000AA000000";
					}
					TcpSender.sendMssageAF(2,cmd);
					break;
				case 202: // 休眠
					if (!MainActivity.musicPlaySt) {
						cmd = "*C0019F01E00000010000000";
						TcpSender.sendMssageAF(2,cmd);
					}
					TcpSender.sendMssageAF(2,netCmd);
					map.clear();
					//memDeviceName="";
					break;
				case 203: // Borad cast time
					TcpSender.sendMssageAF(2,netCmd);
					break;
			}
		} else {
			if(device!=null){
				deviceModelParam=device;
			}
			allControl="00";

			String ss;
			bSearchFlag = 0;
			MainActivity.isAirbus = 0;
			String str_zl = format(netCmd);
			String string_zhiLing ="";
			String pinying = getPinYin(netCmd);

			// step 1
			List<Room> spaceName = RoomFactory.getAll();
			int len_g = spaceName.size();
			// 当前区域
			int ArceID=0;
			for (int i = 0; i < len_g; i++) {
				Room room = spaceName.get(i);
				if (str_zl.contains(room.getRoomName())) {
					spaceNameStr=room.getRoomName();
					ArceID=room.getId();
					break;
				}
			}
			List<Device> words;
			if(ArceID>0){
				// 当前区域设备
				words = DeviceFactory.getDevices(ArceID);
			}else{
				words = DeviceFactory.getAll();
			}
			//特殊技能
			// Human-computer interaction
			//听到我说温度太冷了就把空调打开顺便回答今天好吗
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] AskSetup = {"听到我说", "你就回答", "把"};
				for (String str : AskSetup) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if(ActionFlag>1){
					int AskPos=str_zl.indexOf("听到我说");
					if(AskPos!=-1){
						ReturnAct=str_zl;
						int AnsPos=ReturnAct.indexOf("你就回答");
						int ActPos=ReturnAct.indexOf("把");
						String AskStr="";
						String AnsStr="";
						String ActStr="";
						if((AnsPos>0)&&(ActPos>0)){
							if(AnsPos<ActPos){
								AskStr=ReturnAct.substring(AskPos+AskSetup[0].length(),AnsPos);
								AnsStr=ReturnAct.substring(AnsPos+AskSetup[1].length(),ActPos);
								ActStr=ReturnAct.substring(ActPos+AskSetup[2].length());
							}else{
								AskStr=ReturnAct.substring(AskPos+AskSetup[0].length(),ActPos);
								AnsStr=ReturnAct.substring(ActPos+AskSetup[2].length(),AnsPos);
								ActStr=ReturnAct.substring(AnsPos+AskSetup[1].length());
							}
						}else if(ActPos>0){
							AskStr=ReturnAct.substring(AskPos+AskSetup[0].length(),ActPos);
							ActStr=ReturnAct.substring(ActPos+AskSetup[2].length());
						}else if(AnsPos>0){
							AskStr=ReturnAct.substring(AskPos+AskSetup[0].length(),AnsPos);
							AnsStr=ReturnAct.substring(AnsPos+AskSetup[1].length());
						}
						AskStr=AskStr.replace("你就","").replace("就","").replace("同时","").replace("或","").replace("並","");
						AnsStr=AnsStr.replace("你就","").replace("就","").replace("同时","").replace("或","").replace("並","");
						ActStr=ActStr.replace("你就","").replace("就","").replace("同时","").replace("或","").replace("並","");
						Log.e("text","Ask:"+AskStr+"  Ans:"+AnsStr+"  Act:"+ActStr);
						if((AskStr.length()>0)&&(AnsStr.length()>0||ActStr.length()>0)) {
							//String msg = """Id":"0","VoiceName":"+""你叫什么名字","VoiceAnswer":"我叫牟辉","VoiceAction":"","UserName":"0"
							//ResponseActionInfo.addVoice(msg);
							VoiceInfo voiceInfo = new VoiceInfo();
							if (voiceInfo != null) {
								int num = 0;
								voiceInfo.setVoiceName(AskStr);
								voiceInfo.setVoiceAnswer(AnsStr);
								voiceInfo.setVoiceAction(ActStr);
								voiceInfo.setUserName("0");
								num = VoiceFactory.isExite(voiceInfo.getVoiceName(),
										voiceInfo.getVoiceAnswer());
								if (num == 0) {
									Sqlite().insertVoice(voiceInfo);
									MainActivity.playSound(5, "好的主人,我學會了");
									VoiceFactory.clearList();
								} else {
									MainActivity.playSound(
											5,
											"智能问答"
													+ MyApplication.getInstance()
													.getString(R.string.exist));
								}
							}
						}else{
							MainActivity.playSound(5, "主人语法不太正確");
						}
						//"Id":"0","VoiceName":"你叫什么名字","VoiceAnswer":"我叫牟辉","VoiceAction":"","UserName":"0"
						MainActivity.isAirbus = 50;
					}
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] LearnName = { "记住", "叫" };
				for (String str: LearnName) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag == 2) {
					cStartPos = str_zl.indexOf(LearnName[1]);
					PlayFreeBack = str_zl.substring(cStartPos + 1);
					if (!PlayFreeBack.equals("")) {
						for (Device cmdWords : words) {
							boolean pinyingFlag;
							pinyingFlag=(((cmdWords.getDeviceName().length() >0) && (str_zl.contains(cmdWords.getDeviceName())))|| (PinYinComparison(pinying,
									cmdWords.getDeviceName())));
							if (pinyingFlag) {
								MainActivity.isAirbus = 30;
								int isContains=0;
								String[] nickNames=cmdWords.getDeviceNickName().split(",");
								if(nickNames.length>0){
									for (int i=0;i<nickNames.length;i++){
										if (nickNames[i].contains(
												PlayFreeBack)) {
											isContains=1;
											break;
										}
									}
								}
								if (isContains==0) {
									if(nickNames.length>0){
										for (int i=0;i<nickNames.length;i++) {
											if (!nickNames[i].equals("")) {
												if(string_zhiLing.length()==0){
													string_zhiLing=nickNames[i];
												}else{
													string_zhiLing+=","+nickNames[i];
												}
											}
										}
									}
									if(string_zhiLing.length()==0){
										string_zhiLing =PlayFreeBack;
									}else{
										string_zhiLing = string_zhiLing+","+PlayFreeBack;
									}

									cmdWords.setDeviceNickName(string_zhiLing);
									int num = Sqlite().insertDevice(cmdWords);
									if ((num == 1) || (num == 2)) {
										MainActivity.playSound(3, "好的已經记住"
												+ cmdWords.getDeviceName()
												+ "叫" + PlayFreeBack);
										DeviceFactory.clearList();
									}
								} else {
									MainActivity.playSound(3,
											"主人" + PlayFreeBack + "已經记住是"
													+ cmdWords.getDeviceName()
													+ "的小名");
								}
								break;
							}
						}
						if (MainActivity.isAirbus == 0) {
							MainActivity.playSound(3, "主人找不到" + str_zl);
						}
					} else {
						//
						MainActivity.playSound(3, "主人语法不太正確,你可以說叮咚叮咚记住窗帘叫小可愛");
					}
					//memDeviceName="";
					MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] CancelName = { "取消", "所有", "全部", "设备", "装置", "叫", "的" };
				for (String str: CancelName) {
					//if ((str_zl.contains(str))||(PinYinComparison(pinying, str))) {// 有识别词
					if (str_zl.contains(str)){
						ActionFlag++;
					}
				}
				cStartPos = str_zl.indexOf(CancelName[5]);
				cEndPos = str_zl.indexOf(CancelName[6]);
				if(cEndPos==-1){
					cEndPos=str_zl.length();
				}
				if (cEndPos > cStartPos) {
					PlayFreeBack = str_zl.substring(cStartPos + 1,
							cEndPos);
					if (ActionFlag > 4) {
						if (PlayFreeBack.length() > 0) {
							ActionFlag = 0;
							for (Device cmdWords : words) {
								if (cmdWords.getDeviceNickName().contains(
										PlayFreeBack)) {
									String[] NickName = cmdWords.getDeviceNickName().split(",");
									ReturnAct="";
									for (String str: NickName) {
										if (str.contains(PlayFreeBack)){
											str="";
										}
										if(str.length()>0) {
											if (ReturnAct.length() > 0) {
												ReturnAct+="," + str;
											}else{
												ReturnAct=str;
											}
										}
									}
									//ReturnAct = cmdWords.getDeviceNickName()
									//		.replace(PlayFreeBack, "");
									//ReturnAct = ReturnAct.replace(",,", ",");
									cmdWords.setDeviceNickName(ReturnAct);
									int num = Sqlite().insertDevice(cmdWords);
									if ((num == 1) || (num == 2)) {
										ActionFlag=1;
									}
								}
							}
							if (ActionFlag > 0) {
								MainActivity.playSound(3, "好的已經" + str_zl);
								DeviceFactory.clearList();
							} else {
								MainActivity.playSound(3, "主人沒有设备叫"
										+ PlayFreeBack + "這個小名");
							}
							//memDeviceName="";
							MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
						}
						//else{
						//	MainActivity.playSound(3, "主人语法不太正確,你可以說取消所有设备叫小可愛的");
						//}
					}else if (ActionFlag >= 2) {
						if (PlayFreeBack.length() > 0) {
							for (Device cmdWords : words) {
								boolean pinyingFlag;
								pinyingFlag=(((cmdWords.getDeviceName().length() >0) && (str_zl.contains(cmdWords.getDeviceName())))|| (PinYinComparison(pinying,
										cmdWords.getDeviceName())));
								if (pinyingFlag) {
									MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
									if (cmdWords.getDeviceNickName().contains(
											PlayFreeBack)) {
										String[] NickName = cmdWords.getDeviceNickName().split(",");
										ReturnAct="";
										for (String str: NickName) {
											if (str.contains(PlayFreeBack)){
												str="";
											}
											if(str.length()>0) {
												if (ReturnAct.length() > 0) {
													ReturnAct+="," + str;
												}else{
													ReturnAct=str;
												}
											}
										}
										//string_zhiLing = cmdWords
										//		.getDeviceNickName().replace(
										//				PlayFreeBack, "");
										//string_zhiLing = string_zhiLing.replace(
										//		",,", ",");
										cmdWords.setDeviceNickName(ReturnAct);
										int num = Sqlite().insertDevice(cmdWords);
										if ((num == 1) || (num == 2)) {
											MainActivity.playSound(3, "好的已經取消"
													+ cmdWords.getDeviceName()
													+ "叫" + PlayFreeBack);
											DeviceFactory.clearList();
										}
									} else {
										MainActivity.playSound(3,
												"主人" + cmdWords.getDeviceName()
														+ "沒有" + PlayFreeBack
														+ "這個小名");
									}
									break;
								}
							}
							if (MainActivity.isAirbus == 0) {
								MainActivity.playSound(3, "主人找不到" + str_zl);
							}
						} else {
							MainActivity.playSound(3, "主人语法不太正確,你可以說叮咚叮咚取消窗帘叫小可愛");
						}
						//memDeviceName="";
						MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
					}
				}
			}

			if (MainActivity.isAirbus == 0) {
				if(MainActivity.preAlarmNum>0){
					ActionFlag = 0;
					String[] CancelAlarm = { "清除","取消", "所有", "通知" ,"播报"};
					for (String str: CancelAlarm) {
						if ((str_zl.contains(str))||(PinYinComparison(pinying, str))) {// 有识别词
							ActionFlag++;
						}
					}
					if (ActionFlag > 2) {
						MainActivity.preAlarmNum=0;
						MainActivity.preAlarmStr = "";
						MainActivity.playSound(4, "清除所有通知");
						MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
					}
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] CancelName = { "取消", "所有", "会议", "預約", "约会", "行程",
						"定时"};
				for (String str: CancelName) {
					if ((str_zl.contains(str))||(PinYinComparison(pinying, str))) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag > 2) {
					for (int i = 0; i < 20; i++) {
						Prctime[i] = 0;
						EnableDate[i] = "";
					}
					MainActivity.playSound(3, "好的已經" + str_zl);
					MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
					//memDeviceName="";
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String KewWord[] = { "提醒我", "通知我", "叫我" };
				for (String str: KewWord) {
					cStartPos = str_zl.indexOf(str);
					if (cStartPos != -1) {
						bSearchFlag = str.length();
						break;
					}
				}
				if (cStartPos != -1) {
					String RetTime = GettimePara(str_zl);
					String[] Timeformat = RetTime.split(":");
					long TimeVal = (Integer.parseInt(Timeformat[1]) * 3600)
							+ (Integer.parseInt(Timeformat[2]) * 60)
							+ Integer.parseInt(Timeformat[3]);
					if (!Timeformat[0].equals("0") && (TimeVal > 0)) {
						cEndPos = Integer.parseInt(Timeformat[4]);
						cStartPos = (cStartPos < cEndPos) ? cEndPos
								: (cStartPos + (bSearchFlag - 1));
						bSearchFlag = 0;
						PlayFreeBack = str_zl.substring(cStartPos + 1);
						for (Device cmdWords : words) {
							string_zhiLing = (cmdWords.getDeviceName() + "," + cmdWords
									.getDeviceNickName()).replace(";", ",");
							String[] AbsName = string_zhiLing.split(",");
							for (String cmdSubs : AbsName) {
								if (!"".equals(cmdSubs) && cmdSubs != null) {
									CampStr = cmdSubs;
									boolean pinyingFlag;
									pinyingFlag=(str_zl.contains(CampStr))||PinYinComparison(pinying,
											CampStr);
									if (pinyingFlag) {// 有识别词
										bSearchFlag++;
										break;
									}
								}
							}
						}
						if (bSearchFlag == 0) {
							// "灯光全开", "灯光全关"
							if ((str_zl.contains("灯光全开"))
									|| (str_zl.contains("灯光全关"))) {
								bSearchFlag = 1;
							}
						}
						if (Timeformat[0].equals("1")) {
							ReturnAct = ReturnAct + "后提醒你";
							for (cStartPos = 0; cStartPos < 20; cStartPos++) {
								if (Prctime[cStartPos] == 0) {
									break;
								}
							}
							if (cStartPos < 20) {
								PrcType[cStartPos] = (bSearchFlag > 0) ? 0 : 1;
								PrcWords[cStartPos] = PlayFreeBack;
								Prctime[cStartPos] = (int) TimeVal;
								ReturnAct = ("好的主人" + ReturnAct + PlayFreeBack);
							} else {
								ReturnAct = ("对不起主人,預約服务已経滿了.你真太忙了該好好休息一下");
							}
							MainActivity.playSound(5, ReturnAct);
						} else if (Timeformat[0].equals("2")) {
							Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
							String str = dateToString(curDate, "HH:mm");
							long NowTime = stringToLong(str, "HH:mm");
							long decStart = stringToLong(Timeformat[1] + ":"
									+ Timeformat[2], "HH:mm");
							ReturnAct = ReturnAct + "提醒你";
							if ((str_zl.contains("明天"))
									|| (str_zl.contains("后天"))) {
								GregorianCalendar gc = new GregorianCalendar();
								gc.setTime(curDate);
								if (str_zl.contains("明天")) {
									ReturnAct = "明天" + ReturnAct;
									gc.add(gc.DAY_OF_MONTH, 1);
								} else {
									ReturnAct = "后天" + ReturnAct;
									gc.add(gc.DAY_OF_MONTH, 2);
								}
								str = dateToString(gc.getTime(), "yyMMdd")
										+ longToString(decStart, "HHmm");
								ActionFlag = 1;
							} else {
								if (decStart > NowTime) {
									str = dateToString(curDate, "yyMMdd")
											+ longToString(decStart, "HHmm");
									ActionFlag = 1;
								} else {
									// error
									ReturnAct = "主人現在的時間是"
											+ dateToString(curDate, "HH:mm")
											+ "已経超过你想设定的时间";
								}
							}
							if (ActionFlag > 0) {
								for (cStartPos = 0; cStartPos < 20; cStartPos++) {
									if ((EnableDate[cStartPos] == null)
											|| (EnableDate[cStartPos].length() < 10)) {
										break;
									}
								}
								if (cStartPos < 20) {
									PrcSchType[cStartPos] = (bSearchFlag > 0) ? 0 : 1;
									PrcSchWords[cStartPos] = PlayFreeBack;
									EnableDate[cStartPos] = str;
									ReturnAct = ("好的主人" + ReturnAct + PlayFreeBack);
								} else {
									ReturnAct = ("对不起主人,預約服务已経滿了.你真太忙了該好好休息一下");
								}
							}
							MainActivity.playSound(5, ReturnAct);
						}
						MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
						//memDeviceName="";
					}
					/*
					 * //吃药吃饭 看电影看电视运动起床开会约会订饭店订酒店五点后叫我起床六点提醒我吃药 String[]
					 * CancelName =
					 * {"出门","吃药","吃饭","作饭","看电影","看电视","运动","起床","开会"
					 * ,"约会","订饭店","订酒店"};
					 */
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] Environmental = { "告诉我", "请问","现在", "目前","当前", "室内","室外","客厅","餐厅","父母","主人","卧室","儿童","环境","温湿度","温度", "湿度",  "25",
						"甲醛","亮度","照明" };
				for (String str: Environmental) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag >2) {
					String[] Environmental_Type = { "温湿度","温度", "湿度",  "25",
							"甲醛","亮度","照明" };
					for (int i = 0; i < Environmental_Type.length; i++) {
						if (str_zl.contains(Environmental_Type[i])) {// 有识别词
							if(str_zl.contains("室外")) {
								WeatherInfo info = WeatherUtils.getWeatherInfo();
								if (info != null) {
									switch (i) {
										case 0:
											ReturnAct="目前室外温度"+info.getTemp()+"度C,湿度"+info.getHumidity();
											break;
										case 1:
											ReturnAct="目前室外"+Environmental_Type[i]+info.getTemp()+"度,C";
											break;
										case 2:
											ReturnAct="目前室外"+Environmental_Type[i]+info.getHumidity();
											break;
										case 3:
											ReturnAct="目前室外PM"+Environmental_Type[i]+ "是" +info.getPm25();
											break;
										case 4:ReturnAct="主人,不好意思当前沒有資料.";
											break;
									}
								}else{
									ReturnAct="主人,不好意思当前沒有資料.";
								}
								MainActivity.playSound(5, ReturnAct);
							}else {
								bSearchFlag = 255;
								String[] EnSpaceName = {"室内", "客厅", "餐厅","卧室", "父母", "主人", "儿童"};
								ActionFlag=0;
								for(String str:EnSpaceName){
									if(str_zl.contains(str)){
										bSearchFlag=ActionFlag;
										ReturnAct = "目前" + str;
										if(bSearchFlag>3) {
											ReturnAct+="房";
										}
										break;
									}
									ActionFlag++;
								}
								if(bSearchFlag<255){
									switch (i) {
										case 0:
											ReturnAct=ReturnAct+"温度"+MainActivity.insideTemp[bSearchFlag]+"度,C,湿度"+MainActivity.Humidity[bSearchFlag]+"百分比";
											break;
										case 1:
											ReturnAct=ReturnAct+Environmental_Type[i]+MainActivity.insideTemp[bSearchFlag]+"度,C";
											break;
										case 2:
											ReturnAct=ReturnAct+Environmental_Type[i]+MainActivity.Humidity[bSearchFlag]+"百分比";
											break;
										case 3:
											//ReturnAct=ReturnAct+"PM"+Environmental_Type[i]+ "是"+MainActivity.pm25[bSearchFlag];
											int PM2_5=MainActivity.pm25[bSearchFlag];
											if(PM2_5>0) {
												if (PM2_5 < 35) {
													ReturnAct = "主人你好,目前环境PM25每平方米是" + PM2_5 + ",空气貭量优";
												} else if (PM2_5 < 75) {
													ReturnAct = "主人你好,目前环境PM25每平方米是" + PM2_5 + ",空气貭量良好";
												} else if (PM2_5 < 115) {
													ReturnAct = "主人你好,目前环境PM25每平方米是" + PM2_5 + ",空气貭量属於軽度污染";
												} else if (PM2_5 < 150) {
													ReturnAct = "主人你好,目前环境PM25每平方米是" + PM2_5 + ",空气貭量属於中度污染";
												} else if (PM2_5 < 250) {
													ReturnAct = "主人你好,目前环境PM25每平方米是" + PM2_5 + ",空气貭量属於重度污染";
												} else {
													ReturnAct = "主人你好,目前环境PM25每平方米是" + PM2_5 + ",空气貭量属於严重污染";
												}
											}else{
												ReturnAct="主人,不好意思"+ReturnAct+"沒有資料.";
											}
											break;
										case 4:
											//ReturnAct=ReturnAct+Environmental_Type[i]+MainActivity.formaldehyde[bSearchFlag];
											int formaldehyde=MainActivity.formaldehyde[bSearchFlag];
											if (formaldehyde > 0) {
												if (formaldehyde < 60) {
													ReturnAct = "主人你好,目前甲醛浓度空气中每平方米是" + formaldehyde + ",空气貭量优";
												} else if (formaldehyde < 100) {
													ReturnAct = "主人你好,目前甲醛浓度空气中每平方米是" + formaldehyde + ",注意兒童就会发生轻微气喘";
												} else if (formaldehyde < 500) {
													ReturnAct = "主人你好,目前甲醛浓度空气中每平方米是" + formaldehyde + ",注意空气中有異味和不適感";
												} else {
													ReturnAct = "主人你好,目前甲醛浓度空气中每平方米是" + formaldehyde + ",注意空气貭量属於严重污染";
												}
											}else{
												ReturnAct="主人,不好意思"+ReturnAct+"沒有資料.";
											}
											break;
										case 5:
										case 6:
											ReturnAct=ReturnAct+Environmental_Type[i]+MainActivity.Humidity[bSearchFlag]+"流明";
											//	ReturnAct="目前室內"+Environmental_Type[i]+MainActivity.illumination;
											break;
									}
									MainActivity.playSound(5, ReturnAct);
								}
							}
							MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
							break;
						}
					}
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] addEnvironmental = { "请","我要" ,"添加", "室内","客厅","餐厅","父母","主人","卧室","儿童","传感器" };
				for (String str: addEnvironmental) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag >2) {
					bSearchFlag = 255;
					String[] EnSpaceName = {"室内", "客厅", "餐厅", "卧室", "父母", "主人", "儿童"};
					ActionFlag=0;
					for(String str:EnSpaceName){
						if(str_zl.contains(str)){
							bSearchFlag=ActionFlag;
							ReturnAct=str;
							break;
						}
						ActionFlag++;
					}
					if(bSearchFlag<255){
						MainActivity.addSensorTime=15;
						MainActivity.addSensorId=bSearchFlag;
						if(str_zl.contains("照度")||str_zl.contains("照明")||str_zl.contains("亮度")){
							MainActivity.addSensorId+=16;
						}
						MainActivity.playSound(5, "請按下你要配對的传感器");
					}
					MainActivity.isAirbus = 30;
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] ServerIp = {"告诉我", "请问", "目前", "当前", "服务器"};
				for (String str : ServerIp) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag >2) {
					String hostIP = ProjectUtils.getRootPath()
							.getServiceIP();
					if (hostIP.equals("103.40.22.138")) {
						MainActivity.playSound(5, "当前连接到1号和利扬服务器");
					} else if (hostIP.equals("60.251.48.20")) {
						MainActivity.playSound(5, "当前连接到2号创力特服务器");
					}
					MainActivity.isAirbus = 30;
					//bSearchFlag = 1;
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] ServerIp = {"告诉我", "请问", "目前", "当前", "城市","位置"};
				for (String str : ServerIp) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag >2) {
					String city = ProjectUtils.getRootPath().getCity();
					if (city!=null&& !city.equals("")) {
						MainActivity.playSound(5, "当前城市是"+city);
					} else{
						MainActivity.playSound(5, "未设置当前城市");
					}
					MainActivity.isAirbus = 30;
					//bSearchFlag = 1;
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] changServer = {"设置", "选择",
						"切换", "服务器"};
				for (String str:changServer) {
					if (str_zl.contains(str)) {
						// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag >= 2) {
					int timeVal = timeComprartion(1,
							0, str_zl);
					if ((timeVal == 1)
							||
							(str_zl.contains("和利扬"))
							||
							PinYinComparison(pinying, "和利扬")) {// 有识别词
						MainActivity.playSound
								(5, "已切换到1号和利扬服务器");

						ProjectUtils.getRootPath().setServiceIP(

								"103.40.22.138");

						ProjectUtils.saveRootPath();

						MainActivity.activity.client

								.setHostIP("103.40.22.138");
						SocketClient.isLinkFlag = 5;
						SocketClient.plusNumber = 0;

						MainActivity.activity.client.Connection();
					} else if ((timeVal == 2)
							||
							(str_zl.contains("创力特"))
							||
							PinYinComparison(pinying, "创力特")) {// 有识别词
						MainActivity.playSound
								(5, "已切换到2号创力特服务器");

						ProjectUtils.getRootPath().setServiceIP(

								"60.251.48.20");

						ProjectUtils.saveRootPath();

						MainActivity.activity.client

								.setHostIP("60.251.48.20");
						SocketClient.isLinkFlag = 5;
						SocketClient.plusNumber =0;
						//
						MainActivity.activity.client.Connection();
					} else if ((timeVal == 3)
							||
							(str_zl.contains("本地"))
							||
							PinYinComparison(pinying, "本地")) {// 有识别词
						MainActivity.playSound
								(5, "已切换到3号本地服务器");

						ProjectUtils.getRootPath().setServiceIP("192.168.2.124");

						ProjectUtils.saveRootPath();

						MainActivity.activity.client.setHostIP("192.168.2.124");
						SocketClient.isLinkFlag
								= 5;
						SocketClient.plusNumber
								= 0;
						//
						MainActivity.activity.client.Connection();
					}
					MainActivity.isAirbus = 30;
					//bSearchFlag = 1;
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				String[] changSpace = {"选择", "切换", "空间", "房间"};
				//for (int i = 0; i < changSpace.length; i++) {
				for(String str : changSpace){ //变量n代表被遍历到的数组元素  
					//if (str_zl.contains(changSpace[i])) {// 有识别词
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if (ActionFlag >= 2) {
					List<Room> list = RoomFactory.getAll();
					String result = "您切换的空间不存在";
					if (str_zl.contains("首页")
							|| str_zl.contains("主页")) {
						roomName = "";
						result = "主人,切换到主页";
					} else {
						for (int i = 0; i < list.size(); i++) {
							if (str_zl.contains(list.get(i)
									.getRoomName())) {
								roomName = list.get(i)
										.getRoomName();
								result = "主人,切换到" + roomName;
								break;
							}
						}
					}
					MainActivity.playSound(5, result);
					MainActivity.isAirbus = 30;
					//bSearchFlag = 1;
				}
			}
			if (MainActivity.isAirbus == 0) {
				ActionFlag = 0;
				//叮咚叮咚，你有哪些技能，你都会干啥，你会做啥。你有啥本事
				String[] Skill={"你","可以","有","会","能","技能","干啥","做啥","本事"};
				for (String str : Skill) {
					if (str_zl.contains(str)) {// 有识别词
						ActionFlag++;
					}
				}
				if(ActionFlag>2){
					if(str_zl.contains("告诉我")) {
						String[] SkillAsk = {"..主人我現在可牛逼了..一.智能家居控制是我的專長,你可以說空調打開,筒燈關閉", "二.数值计算,您可以这样提问,45的三次方或根号76",
								"三.时间、日期的查询,如今天星期几,距离春节还有多久,几点了", "四.菜谱的查询,茄子怎么烧或尖椒炒鸡蛋怎么做",
								"五.互动百科词条查询,你可以說百科搜索张学友,毛澤東的百科", "六.英语每日一句,我要学英语,来一句英语",
								"七.查询星座，及星座特征，运势等属性,射手座的爱情运势", "八.音乐的搜索和播放,播放刘德华的忘情水",
								"九.新闻的搜索和点播,给我讲个新闻或有什么社会新闻", "十.笑话的点播,我想听笑话", "第十一诗词查询和诗句对答,给我背白居易的诗",
								"十二.天气情况的查询,查看北京今天的天气,上海天气怎么样", "十三.中英翻译,把麻婆豆腐翻译成英文或苹果英文怎么说",
								"十四.股票信息查询,今天的港股大盘或科大讯飞的行情", "十五.故事的点播,讲个故事或我想听安徒生写的故事",
								"十六.闹钟提醒订明天早上八点闹钟或订明天早上九点开会", "十七.词汇近反义词的查询,煎熬的近义词安静的近义词是什么",
								"十八.猜谜语,還有我會一直努力學習成長,總之能夠為主人你服務是我的榮幸"};
						//MainActivity.playSound(5, "我有很多技能等你體驗喔");
						List<SongPlayInfo> playList = new ArrayList<>();
						for (String str : SkillAsk) {
							//JSONObject newsJson = result.optJSONObject(index);
							//String steps="第" + (index+1) + newsJson.getString("steps");
							SongPlayInfo songPlayInfo = new SongPlayInfo();
							songPlayInfo.setPlayUrl(str);
							playList.add(songPlayInfo);
						}
						if (MusicPlayMedia.getInstansMedia() != null) {
							MusicPlayMedia.getInstansMedia().playControllerURLList("", playList);
							MusicPlayMedia.getInstansMedia().playControllerText("", playList.get(0).getPlayUrl(), true, "", null);
						}
						MainActivity.isAirbus = 30;
						//bSearchFlag = 1;
					}
				}
			}

			if((repetition!=2)&&(MainActivity.isAirbus==0)) {//自問答功能
				ReturnAct = "没有找到识别的设备";
				List<VoiceInfo> voiceInfo = VoiceFactory
						.getVoiceInfo(str_zl, pinying);
				if (voiceInfo.size() > 0) {
					bSearchFlag++;
					MainActivity.isAirbus = 30;
					Random ra = new Random();
					int radom = ra.nextInt(voiceInfo.size());
					if (radom == voiceInfo.size()) {
						radom = 0;
					}
					for (int i = 0; i < voiceInfo.size(); i++) {
						ReturnAct = voiceInfo.get(i)
								.getVoiceAnswer();
						String action = voiceInfo.get(i)
								.getVoiceAction();
						if ((action != null) && (action.length() > 0)) {
							if (voiceInfoAction(action, i, radom)) {
								break;
							}
						} else {
							if (i == radom) {
								MainActivity.playSound(4, ReturnAct);
								break;
							}
						}
					}
				}
				/*
				//if (ActionFlag == 0) {
					//if (onlyPlayAnswer) {
					//	return;
					//}

						ReturnAct = voiceInfo.get(radom)
								.getVoiceAnswer();
						String action = voiceInfo.get(radom)
								.getVoiceAction();
						bSearchFlag++;
						MainActivity.isAirbus = 30;
						if ((action != null) && (action.length() > 0)) {
							onlyPlaySound = true;
							//onlyPlayAnswer = true;
							voiceInfoAction(action);
						} else {
							//?(type,type,type)
							MainActivity.playSound(4, ReturnAct);
						}
					}
				//}
				*/
			}
			//特殊技能結尾
			if (MainActivity.isAirbus == 0) {
				//先檢查權開關
				// step 1
				boolean retBackFlag;
				ActionFlag = 0;
				PlayFreeBack = roomName;
				ss = str_zl;
				for (int i = 0; i < len_g; i++) {
					Room arce = spaceName.get(i);
					if (str_zl.contains(arce.getRoomName())||PinYinComparison(pinying, arce.getRoomName())) {
						//retBackFlag = true;
						ArceID = arce.getId();
						// if (ArceID != 0) {
						String[] ActionFunction = { "灯光", "全部", "全" };
						for (String str:ActionFunction) {
							if (ss.contains(str)) {
								ss=ss.replace(str, "");
								ActionFlag++;
							}
						}
						if (ActionFlag == 2) {
							String[] ActionKey = { "开", "关", "观", "官" };
							for (String str:ActionKey) {
								if (ss.contains(str)) {
									ActionFlag++;
									break;
								}
							}
						}
						PlayFreeBack = arce.getRoomName();
						// PlayFreeBack = roomName;
						break;
					}
				}
				if (ActionFlag >= 3) {
					if (str_zl.contains("开")) {
						ActionFlag = 1;
						PlayFreeBack += "灯光全开";
					} else {
						ActionFlag = 2;
						PlayFreeBack += "灯光全关";
					}
				} else {
					ActionFlag = 0;
					String[] zhiLing = MainActivity.activity.getResources()
							.getStringArray(R.array.lightSate);
					for (int j = 0; j < zhiLing.length; j++) {
						if (str_zl.contains(zhiLing[j])) {
							retBackFlag = false;
							for (int i = 0; i < len_g; i++) {
								Room arce = spaceName.get(i);
								if (str_zl.contains(arce.getRoomName())||PinYinComparison(pinying, arce.getRoomName())) {
									retBackFlag = true;
									ArceID = arce.getId();
									PlayFreeBack = arce.getRoomName();
									break;
								}
							}
							// 此处需注意多语言
							if (str_zl.contains("主页")) {
								str_zl = str_zl.replace("主页", "");
							} else {
								if ((retBackFlag)
										|| ((!retBackFlag) && (ArceID != 0))) {
									ActionFlag = (j + 1);
									PlayFreeBack += zhiLing[j];
								}
							}
							break;
						}
					}
				}
				if (ActionFlag > 0) {
					String replase = "";
					// 当前区域设备
					List<Device> spWords = DeviceFactory.getDevices(ArceID);
					for (Device deviceModel : spWords) {
						deviceProductCode = deviceModel.getProductsCode();
						if (ActionFlag < 5) {
							boolean IsDeviceFlag = false;
							// 由服务器的产品类型增加灯光及设备全开关的旗标
							if ("01".equals(deviceProductCode)
									|| "06".equals(deviceProductCode)
									|| "03".equals(deviceProductCode)
									|| "A3".equals(deviceProductCode)
									|| "27".equals(deviceProductCode)) {
								IsDeviceFlag = true;
							}
							if (IsDeviceFlag) {
								if (replase.length() > 0) {
									replase = replase + ",";
								}
								String ArceDeviceName=deviceModel.getRoomName()+ deviceModel.getDeviceName();
								replase = replase + ArceDeviceName;
								if ((ActionFlag & 1) > 0) {
									// "打开"
									replase = replase + "打开";
								} else {
									// "关闭"
									replase = replase + "关闭";
								}
								MultiFlag++;
							}
						} else {
							int productId = Integer.parseInt(deviceProductCode, 16);
							if ((productId != 5) && (productId != 7)
									&& (productId != 255) && (productId != 101)) {
								if (replase.length() > 0) {
									replase = replase + ",";
								}
								String ArceDeviceName=deviceModel.getRoomName()+ deviceModel.getDeviceName();
								replase = replase + ArceDeviceName + "关闭";
								MultiFlag++;
							}
						}
					}
					str_zl = replase;
					pinying = "";
					onlyPlaySound = true;
					MainActivity.playSound(2, PlayFreeBack);
				}
				// step 2
				bSearchFlag = 0;
				MultiFlag = 0;
				// 所有设备
				if (words.size() > 0) {
					if (ArceID > 0) {
						str_zl = spaceNameStr + str_zl;
					}
					if (str_zl.contains("设备全关")) {
						if (ArceID <= 0) {
							String replase = "";
							for (int d = 0; d < words.size(); d++) {
								if (words.get(d).getRoomId() == 0) {
									continue;
								}
								Device cmdWords = words.get(d);
								int productId = Integer.parseInt(
										cmdWords.getProductsCode(), 16);
								if ((productId != 5) && (productId != 7)
										&& (productId != 255)
										&& (productId != 101)) {
									if (replase.length() > 0) {
										replase = replase + ";";
									}
									String ArceDeviceName=cmdWords.getRoomName()+ cmdWords.getDeviceName();
									replase = replase + ArceDeviceName + "关闭";
									MultiFlag++;
								}
							}
							str_zl = str_zl.replace("设备全关",
									(replase.length() > 0) ? replase : "");
							onlyPlaySound = true;
							MainActivity.playSound(3, "设备已全关");
						}
						MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
						//memDeviceName="";
					} else {
						for (int d = 0; d < words.size(); d++) {
							// deviceModel = words.get(d);()
							if (words.get(d).getRoomId() == 0) {
								continue;
							}
							Device cmdWords = words.get(d);
							string_zhiLing = (cmdWords.getDeviceName() + "," + cmdWords.getDeviceNickName());
							string_zhiLing = string_zhiLing.replace(";", ",").trim();
							string_zhiLing = string_zhiLing.replace("，", ",");
							String[] AbsName = string_zhiLing.split(",");
							for (int s = 0; s < AbsName.length; s++) {
								AbsName[s] = AbsName[s].trim();
								if (!"".equals(AbsName[s])
										&& AbsName[s] != null) {
									CampStr = AbsName[s];
									boolean pinyingFlag;
									pinyingFlag=(str_zl.contains(CampStr))||PinYinComparison(pinying,
											CampStr);
									if (pinyingFlag) {// 有识别词
										// if (str_zl.indexOf(AbsName[s]) != -1
										// || AbsName[s].indexOf(str_zl) != -1)
										// {// 有识别词
										ss = cmdWords.getDeviceName(); // AbsName[s];
										ActionFlag = 0;
										if ("FF".equals(cmdWords
												.getProductsCode())) {
											if (cmdWords.getDeviceOrdered()
													.length() > 0) {
												String[] Action = cmdWords
														.getDeviceOrdered()
														.replace("，", ",")
														.split(",");

												int len = Action.length;
												if (len > 0) {
													for (int m = 0; m < 20; m++) {
														delayPrctime[m] = 0;
													}
													//ss = "";
													int maxtime = 0;
													for (int z = 0; z < len; z++) {
														String cmdWord = Action[z];
														if (cmdWord.length() > 0) {
															int checkStart = Action[z]
																	.indexOf("(");
															int checkEnd = Action[z]
																	.indexOf(")");
															String Period = "00:00--00:00";
															if ((checkStart != -1)
																	&& (checkEnd != -1)
																	&& (checkEnd > checkStart)) {
																Period = Action[z]
																		.substring(
																				checkStart + 1,
																				checkEnd);
																cmdWord = Action[z]
																		.replace(
																				"("
																						+ Period
																						+ ")",
																				"");
															}
															String[] periodArr = Period
																	.split("--");
															if (checkPeriod(
																	periodArr[0],
																	periodArr[1])) {
																String value = "1";
																cStartPos = Action[z]
																		.indexOf("#");
																if (cStartPos != -1) {
																	value = cmdWord
																			.substring(cStartPos + 1);
																	cmdWord = cmdWord
																			.substring(
																					0,
																					cStartPos);
																}
																if (maxtime < 20) {
																	delayPrctime[maxtime] = Integer
																			.parseInt(value);
																	setWords[maxtime] = cmdWord;
																	maxtime++;
																}
															}
															ActionFlag = 1;
														}
													}
												}
											}
											MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
											if (ActionFlag > 0) {
												MainActivity
														.playSound(
																2,
																"好的主人已經打开"
																		+ cmdWords
																		.getDeviceName());
											} else {
												MainActivity
														.playSound(
																2,
																cmdWords.getDeviceName()
																		+ "尚未添加设备");
											}
										} else {
											str_zl = str_zl
													.replace(
															CampStr,
															((MultiFlag > 0) ? ";"
																	: "")
																	+ ss);
											MultiFlag++;
										}
										break;
									}
								}
							}
						}
					}
				}
				if ((str_zl.length() > 0) && str_zl.startsWith(";")) {
					str_zl = str_zl.substring(1);
				}
				String[] allON_OFF = { "灯光全开", "灯光全关", "照明全开", "照明全关", "窗帘全开",
						"窗帘全关", "调光全开", "调关全开", "调光圈开", "调光全关", "调光圈关", "调关全关",
						"彩光全开", "彩光圈开", "彩光全关", "彩光圈关", "打开交互模式", "打开交谈模式",
						"交谈模式打开", "关闭交互模式", "关闭交谈模式", "交谈模式关闭", "开启数据监测",
						"关闭数据监测", "传感器配对", "环境传感器配对", "温湿度传感器配对", "打开语音播报",
						"语音播报打开", "关闭语音播报", "语音播报关闭" ,"打开音量自动调节","关闭音量自动调节",
						"直播一曲","只播一首","播放单曲","取消所有收藏","取消全部收藏","清除所有收藏"};
				int allonofflen = allON_OFF.length;
				for (int all = 0; all < allonofflen; all++) {
					if (str_zl.contains(allON_OFF[all])) {// 有识别词
						ReturnAct = ReturnAct + allON_OFF[all];
						bSearchFlag++;
						MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
						//memDeviceName="";
						switch (all) {
							case 0:// "灯光全开"
							case 2:// "照明全开"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA01FF0000230000FF");
								sendMssageAF(modelflag, "*C0019FA1EFF0000240000FF");
								MainActivity.playSound(1, allON_OFF[all]);
								break;
							case 1:// "灯光全关"
							case 3:// "照明全关"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA01FF0000130000FF");
								sendMssageAF(modelflag, "*C0019FA1EFF0000140000FF");
								MainActivity.playSound(1, allON_OFF[all]);
								break;
							case 4:// "窗帘全开"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA0CFF0000200000FF");
								break;
							case 5:// "窗帘全关"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA0CFF0000100000FF");
								break;
							case 6:// "调光全开"
							case 7:// "调关全开"
							case 8:// "调光圈开"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FAEFF0000240000FF");
								break;
							case 9:// "调光全关"
							case 10:// "调光圈关"
							case 11:// "调关全关"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA1EFF0000140000FF");
								break;
							case 12:// "彩光全开"
							case 13:// "彩光圈开"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA1EFF0000240000FF");
								break;
							case 14:// "彩光全关"
							case 15:// "彩光圈关"
								devieMid1 = "00";
								devieMid2 = "00";
								sendMssageAF(modelflag, "*C0019FA1EFF0000140000FF");
								break;
							case 16:// @开啟交互模式
							case 17:// @交互模式开啟
							case 18:
								ProjectUtils.getRootPath().setInteractive(1);
								ProjectUtils.saveRootPath();
								MainActivity.playSound(2, allON_OFF[all]);
								break;
							case 19:// @关闭交互模式
							case 20:// @"布防"
							case 21:
								ProjectUtils.getRootPath().setInteractive(0);
								ProjectUtils.saveRootPath();
								MainActivity.playSound(2, allON_OFF[all]);
								break;
							case 22:
								MainActivity.backCode = 3;
								MainActivity.playSound(2, allON_OFF[all]);
								break;
							case 23:
								if (MainActivity.backCode > 0) {
									MainActivity.backCode = 0;
								}
								MainActivity.playSound(2, allON_OFF[all]);
								break;
							case 24:
							case 25:
							case 26:
								//sendMssageAF(modelflag, "*C0009AA2400FF0000000000");
								MainActivity.playSound(2, allON_OFF[all]);
								break;
							case 27:
							case 28:
								ProjectUtils.getRootPath().setIsSpeech(0);
								ProjectUtils.saveRootPath();
								MainActivity.playSound(5, allON_OFF[all]);
								break;
							case 29:
							case 30:
								ProjectUtils.getRootPath().setIsSpeech(1);
								ProjectUtils.saveRootPath();
								MainActivity.playSound(5, allON_OFF[all]);
								break;
							case 31:
								ProjectUtils.getRootPath().setIsVoiceAutoAdj(0);
								ProjectUtils.saveRootPath();
								MainActivity.playSound(5, allON_OFF[all]);
								break;
							case 32:
								ProjectUtils.getRootPath().setIsVoiceAutoAdj(1);
								ProjectUtils.saveRootPath();
								MainActivity.playSound(5, allON_OFF[all]);
								break;
							case 33:
							case 34:
							case 35:	MainActivity.musiconlyonce=true;
								break;
							case 36:
							case 37:
							case 38:MusicPlayMedia.getInstansMedia().deleteAll();
								break;
						}
					}
				}
				// Device Redevice = new Device();
				ReturnAct = "";
				for (Device cmdWords : words) {
					deviceModelParam=cmdWords;
					deviceProductCode = cmdWords.getProductsCode();
					// if (deviceProductCode == null) {
					// }
					string_zhiLing = (cmdWords.getDeviceName() + "," + cmdWords.getDeviceNickName());
					string_zhiLing = string_zhiLing.replace(";", ",");
					string_zhiLing = string_zhiLing.replace("，", ",");
					String[] AbsName = string_zhiLing.split(",");
					for (String cmdSubs : AbsName) {
						if (!"".equals(cmdSubs) && cmdSubs != null) {
							CampStr = cmdSubs;
							boolean pinyingFlag;
							pinyingFlag=(str_zl.contains(CampStr))||PinYinComparison(pinying, CampStr);
							if (pinyingFlag) {// 有识别词
								// if (str_zl.indexOf(cmdSubs) != -1) {
								//bSearchFlag++;
								// Redevice=cmdWords;
								// MainActivity.isAirbus++;
								// 增加時間管控 & 人員權限管控 joe
								cStartPos = str_zl.indexOf(cmdWords
										.getDeviceName());
								words_ls = CampStr; // "";
								devieID = cmdWords.getDeviceID();
								devieMid1 = "00";
								devieMid2 = "00";
								SendType = "AA";
								ActionFlag = 0;
								if (devieID.length() == 6) {
									devieID = cmdWords.getDeviceID().substring(
											0, 2);
									devieMid1 = cmdWords.getDeviceID()
											.substring(2, 4);
									devieMid2 = cmdWords.getDeviceID()
											.substring(4, 6);
								}
								deviceIO = "0";
								if (cmdWords.getDeviceIO().length() > 0) {
									deviceIO = cmdWords.getDeviceIO();
								}
								checkPeriodForDeviceModel(cmdWords, modelflag,
										str_zl);
								break;
							}
						}
					}
				}
				// /*
				// if (bSearchFlag == 0) {
				if(repetition!=1) {
					if (bSearchFlag == 0) {
						//系統正式情景模式
						boolean isModeOk = false;
						//cStartPos = 0;
						// 获取所有模式
						List<Mode> sceneArray = ModeFactory.getAll();
						for (int index = 0; index < sceneArray.size(); index++) {
							Mode scene = sceneArray.get(index);
							// joe 2017_08_28
							String nickName = scene.getModeNickName();
							String upString = "";
							int startPos = nickName.indexOf("[");
							int endPos = nickName.indexOf("]");
							if ((startPos != -1) && (endPos != -1)
									&& (endPos > startPos)) {
								upString = nickName.substring(startPos, endPos + 1);
								nickName = nickName.replace(upString, "");
							}
							string_zhiLing = (scene.getModeName() + "," + nickName);
							string_zhiLing = string_zhiLing.replace(";", ",");
							string_zhiLing = string_zhiLing.replace("，", ",");
							String[] AbsName = string_zhiLing.split(",");
							for (String cmdSubs : AbsName) {
								if (!"".equals(cmdSubs) && cmdSubs != null) {
									boolean pinyingFlag;
									pinyingFlag = (str_zl.contains(cmdSubs)) || PinYinComparison(pinying, cmdSubs);
									if (pinyingFlag) {// 有识别词
										bSearchFlag++;
										MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
										isModeOk = true;
										if (checkPeriod(scene.getStartTime(), scene.getEndTime())) {
											String playContains = "執行" + scene.getModeName();
											if (!playContains.contains("模式")) {
												playContains += "模式";
											}
											MainActivity.playSound(3, playContains);
											onlyPlaySound = true;
											//MainActivity.UploadText(upString,1);
											DecodeinfoAction(upString, 1, 1);
											if ("FF".equals(scene.getModeType())) {
												int modelCode = scene.getModeCode();// 场景代码
												String hexString = toHex(modelCode);
												hexString = "*C0032AAFF00FF"
														+ hexString + "00000000";
												sendMssageAF(modelflag, hexString);
											} else {
												// 获取空间集合modelist
												List<ModeList> deviceArray = ModeListFactory
														.getModeDevice(scene.getId());

												int len = deviceArray.size();
												if (len > 0) {
													for (int m = 0; m < 20; m++) {
														delayPrctime[m] = 0;
													}
													//ss = "";
													int maxtime = 0;
													for (int z = 0; z < len; z++) {
														ModeList _device = deviceArray
																.get(z);
														String[] periodArr = _device
																.getModePeriod()
																.split("--");
														if (periodArr.length == 1) {
															periodArr = "00:00--00:00"
																	.split("--");
														}

														if (checkPeriod(periodArr[0],
																periodArr[1])) {
															int startM=0;
															int endM=0;
															if(_device.getBeginMonth().length()>0){
																startM=Integer.valueOf(_device.getBeginMonth().substring(0, 1), 16);
															}
															if(_device.getEndMonth().length()>0){
																endM=Integer.valueOf(_device.getEndMonth().substring(0, 1), 16);
															}
															boolean monthEnable=true;
															if((startM>0)&&(endM>0)&&(startM!=endM)){
																SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
																int NowMonth=Integer.parseInt(dateFormat.format(new Date()));
																if(startM>endM){
																	monthEnable=!((NowMonth>endM&&NowMonth<startM));
																}else{
																	monthEnable=((NowMonth>=startM&&NowMonth<=endM));
																}
															}
															if(monthEnable) {
																String value = "1";
																String cmdWord;
																// 判断t_mode_list表顺序是否等于1
																// cmdWord =
																// _device.getDeviceName()
																// +
																// _device.getModeEvent();
																if (_device
																		.getDeviceTypeKey() == 20) {
																	String AreStr = "";
																	if (_device
																			.getModeEvent()
																			.equals("灯光全开")
																			|| _device
																			.getModeEvent()
																			.equals("灯光全关")) {
																		AreStr = "主页";
																	}
																	cmdWord = AreStr+_device.getModeFunction();
																} else {
																	cmdWord=_device.getRoomName()+_device.getDeviceName()+_device.getModeAction()+_device.getModeFunction()+_device.getModeTime();
																}
																String delay = AppTools.getNumbers(_device
																		.getModeDelayed().replace("秒",""));
																if ((Integer
																		.parseInt(delay)) > 0) {
																	value = delay;
																}
																if (maxtime < 20) {
																	delayPrctime[maxtime] = Integer
																			.parseInt(value);
																	setWords[maxtime] = cmdWord;
																	maxtime++;
																}
															}
														}
													}
												}
											}
										}
										//else {
										// 显示时间管控无法执行
										//}
										break;
									}
								}
							}
							if (isModeOk) {
								break;
							}
						}
					}
				}
				if (modelflag == 0) {
					String[] musicPlay = {"我想听", "我要听","唱一首", "来一首", "播一首", "放一首", "播放", "放首",
							"来一曲", "唱一手", "来一手", "播一手", "放一手", "放手", "唱首", "来首", "换一首",
							"换一手", "换一曲","给我背","我想问","说一个","说个","讲一个","讲个"};
					for (String str: musicPlay) {
						if (str_zl.contains(str)) {// 有识别词
							MainActivity.musicIsSong = true;
							break;
						}
					}
					if (bSearchFlag == 0) {
						/*
						if(memDeviceName.length()>0){
							String[] actionStr={"打开","关闭","静音","温度","色","光","制冷","制熱","度"};
							for (String str: actionStr) {
								if (str_zl.contains(str)) {// 有识别词
									for (ActionFlag = 0; ActionFlag < 20; ActionFlag++) {
										if (voiceInfoTime[ActionFlag] == 0) {
											break;
										}
									}
									if (ActionFlag < 20) {
										String ActionStr=memDeviceName+str_zl;
										int delayPos = ActionStr.indexOf("#");
										if (delayPos != -1) {
											int timeValue = timeComprartion(1, delayPos, ActionStr);
											voiceInfoTime[ActionFlag] = timeValue;
											voiceInfoStr[ActionFlag] = ActionStr.substring(0, delayPos);
										} else {
											voiceInfoTime[ActionFlag] = 1;
											voiceInfoStr[ActionFlag] = ActionStr;
										}
										voiceType[ActionFlag]=1;
									}
									MainActivity.isAirbus = 30;
									break;
								}
							}
						}
						*/
						//控制叮咚的音量
						boolean wakeUpClose=false;
						//if (bSearchFlag == 0) {
						String[] volMax = {"音量最大", "声音最大", "音量开最大", "声音开最大", "音量全开", "声音全开"};
						for (String str: volMax) {
							if (str_zl.contains(str)) {// 有识别词
								if (MusicPlayMedia.getInstansMedia() != null) {
									MusicPlayMedia.setVolume(100);
								}
								wakeUpClose=true;
								//bSearchFlag = 1;
								break;
							}
						}
						//}
						if (!wakeUpClose) {
							String[] volMin = {"音量最小", "声音最小", "音量开最小", "声音开最小", "音量关最小", "声音关最小"};
							for (String str: volMin) {
								if (str_zl.contains(str)) {// 有识别词
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setVolume(10);
									}
									wakeUpClose=true;
									//bSearchFlag = 1;
									break;
								}
							}
						}
						if (!wakeUpClose) {
							String[] volAdd = {"音量加", "声音加", "声音大", "音量大", "声音大一点", "音量大一点",
									"声音太小了", "音量太小了", "音量高一点", "音量加一点", "音量再加一点", "音量再大一点"};
							for (String str: volAdd) {
								if (str_zl.contains(str)) {// 有识别词
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setUpVolume();
									}
									wakeUpClose=true;
									//bSearchFlag = 1;
									break;
								}
							}
						}
						if (!wakeUpClose) {
							String[] volSub = {"音量减", "声音减", "音量小", "声音小", "声音小一点", "音量小一点", "声音太大了",
									"音量太大了", "音量低一点", "声音低一点", "音量再小一点", "声音再小一点", "音量太大了"};
							for (String str: volSub) {
								if (str_zl.contains(str)) {// 有识别词
									if (MusicPlayMedia.getInstansMedia() != null) {
										MusicPlayMedia.setDownVolume();
									}
									wakeUpClose=true;
									//bSearchFlag = 1;
									break;
								}
							}
						}
						if (!wakeUpClose) {
							String[] volSet = {"音量", "声音","力量"};
							for (String str: volSet) {
								if (str_zl.contains(str)||PinYinComparison(pinying,
										str)) {// 有识别词
									int timeVal = timeComprartion(1, 0, str_zl);
									if (timeVal > 0 && timeVal <= 100) {
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.setVolume(timeVal);
										}
										MainActivity.playSound(4, "音量已设定:" + timeVal);
										wakeUpClose=true;
										//bSearchFlag = 1;
									}
									break;
								}
							}
						}
						//控制叮咚的播放
						boolean wakeUpClosePlay=false;
						String[] pause = {"继续播放","继续播报","恢复播放","重新播放","重新播报","音乐重播","重播一次","再说一次"};
						for (String str: pause) {
							if (str_zl.contains(str)) {// 有识别词
								if (MusicPlayMedia.getInstansMedia() != null) {
									MusicPlayMedia.getInstansMedia().continuePlay();
								}
								MainActivity.musicIsSong=false;
								wakeUpClosePlay=true;
								//bSearchFlag = 1;
								break;
							}
						}
						if (!wakeUpClosePlay) {
							String[] resume = {"暂停所有播放","暂停所有播报", "停止所有播放", "停止所有播报","所有播放暂停", "所有播放停止","暂停播放","暂停播报", "停止播放", "停止播报","播放暂停", "播放停止","音乐暂停","音乐停止"
							};
							for (String str: resume) {
								if (str_zl.contains(str)) {// 有识别词
									if(str_zl.contains("所有")){
										if(MainActivity.musicTTsSt) {
											if (MusicPlayMedia.getInstansMedia() != null) {
												MusicPlayMedia.getInstansMedia().pause();
											}
										}
										if(MainActivity.musicPlaySt) {
											if (MusicPlayMedia.getInstansMedia() != null) {
												MusicPlayMedia.getInstansMedia().pause();
											}
										}
									}else {
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().pause();
										}
									}
									MainActivity.musicIsSong=false;
									wakeUpClosePlay=true;
									//bSearchFlag = 1;
									break;
								}
							}
						}
						if(MainActivity.musicIsSong) {
							if (!wakeUpClosePlay) {
								String[] next = {"下一首", "下一曲", "下一取", "下一娶", "下一手", "下一守"};
								for (String str : next) {
									if (str_zl.contains(str)) {// 有识别词
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().next();
										}
										MainActivity.musicIsSong = false;
										wakeUpClosePlay = true;
										//bSearchFlag = 1;
										break;
									}
								}
							}
							if (!wakeUpClosePlay) {
								String[] previous = {"上一首", "上一曲", "上一取", "上一娶", "上一手", "上一守"};
								for (String str : previous) {
									if (str_zl.contains(str)) {// 有识别词
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().previous();
										}
										MainActivity.musicIsSong = false;
										wakeUpClosePlay = true;
										//bSearchFlag = 1;
										break;
									}
								}
							}
							if (!wakeUpClosePlay) {
								String[] lastPlay = {"最后一首", "最后一曲", "最后一娶", "最后一手", "最后一守"};
								for (String str : lastPlay) {
									if (str_zl.contains(str)) {// 有识别词
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().playLast();
										}
										MainActivity.musicIsSong = false;
										wakeUpClosePlay = true;
										//bSearchFlag = 1;
										break;
									}
								}
							}
							if (!wakeUpClosePlay) {
								String[] PlayNumber = {"第", "首", "曲", "娶", "手", "守"};
								ActionFlag = 0;
								for (String str : PlayNumber) {
									if (str_zl.contains(str)) {// 有识别词
										ActionFlag++;
									}
								}
								if (ActionFlag > 1) {
									int timeVal = timeComprartion(1, 0, str_zl);
									if (timeVal > 0 && timeVal <= 20) {
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().playNumber(timeVal);
										}
										MainActivity.musicIsSong = false;
										wakeUpClose = true;
										//bSearchFlag = 1;
									}
								}
							}
						}
						if(wakeUpClose||wakeUpClosePlay){
							MainActivity.isAirbus = 30;
							/*
							MainActivity.isUploadText="";
							MainActivity.isUploadIndex = 0;
							if (MainActivity.mIsWakeUp < 255) {
								// sleep
								MainActivity.activity.resetWakeup(false);
								//voiceInfoTime[19] = 1;
								//voiceInfoStr[19] = "";
								//voiceType[19] = 5;
							}
							*/
						}
					}
					// 放松,轻松
					ActionFlag = 0;
					String[] RelaxStr = {"放松", "轻松", "心灵鸡汤"};
					for (String str: RelaxStr) {
						if (str_zl.contains(str)) {// 有识别词
							ActionFlag++;
						}
					}
					if (ActionFlag > 0) {
						String Quotations="";
						String songName="";
						if (str_zl.contains("早上好")
								|| str_zl.contains("早安")
								|| str_zl.contains("good morning")) {
							Quotations="主人,早上好,你准备好了吗,我现在为你播放我的心灵鸡汤，让我们一起开始新的一天";
							songName=Constants.MORNING;
							bSearchFlag = 1;
							// return;
						} else if (str_zl.contains("午休")
								|| str_zl.contains("中午")) {
							Quotations="主人,忙碌了一上午,躺下来休息一下吧，让我给你解解乏";
							songName=Constants.LAUNCH;
							bSearchFlag = 1;
							// return;
						} else if (str_zl.contains("晚安")
								|| str_zl.contains("晚上")) {
							Quotations="主人,忙碌了一天,让我为你消除一天的疲劳,听听我的声音,做一个好梦，我们开始新的明天";
							songName= Constants.EVENING;
							bSearchFlag = 1;
							// return;
						}
						if(bSearchFlag>0){
							MainActivity.playMusic(1, songName);
							MainActivity.playSound(5,Quotations);
							//MusicPlayMedia.getInstansMedia().playControllerURLList("", null);
							//MusicPlayMedia.getInstansMedia().playControllerText("",Quotations, true, "", null);
							MainActivity.isAirbus = 30;
						}
					}
					if (musicPlayPreSt > 0) {
						if((str_zl.contains("音乐灯光打开"))||(str_zl.contains("打开音乐灯光"))){
							final Random random = new Random();
							MainActivity.sleepLight=random.nextInt(7) + 1;
							String cmd = "*C0019F01E000000AE0" + MainActivity.sleepLight + "0000";
							TcpSender.sendMssageAF(2,cmd);
							MainActivity.isAirbus = 30;
						}else if((str_zl.contains("音乐灯光关闭"))||(str_zl.contains("关闭音乐灯光"))){
							MainActivity.sleepLight=0;
							String cmd = "*C0019F01E00000010000000";
							TcpSender.sendMssageAF(2,cmd);
							MainActivity.isAirbus = 30;
						}else{
							ActionFlag = 0;
							//请将这首歌收藏到我的最爱
							String[] myLove = {"将", "这首歌","添加","收藏","加入","喜爱的歌","喜欢的歌","最爱的歌","我的最爱"};
							for (String str: myLove) {
								if (str_zl.contains(str)) {// 有识别词
									ActionFlag++;
								}
							}
							if (ActionFlag > 2) {
								int reslut=	MusicPlayMedia.getInstansMedia().addSong();
								if(reslut==1) {
									MainActivity.playSound(5,"歌曲已存在收藏列表");
								}else {
									MainActivity.playSound(5,"歌曲收藏成功");
								}
								MainActivity.isAirbus = 30;
							}
							if(MainActivity.isAirbus==0) {
								ActionFlag = 0;
								//请将这首歌收藏到我的最爱
								String[] deleteMyLove = {"将", "这首歌", "刪除", "取消", "收藏"};
								for (String str : deleteMyLove) {
									if (str_zl.contains(str)) {// 有识别词
										ActionFlag++;
									}
								}
								if (ActionFlag > 2) {
									MusicPlayMedia.getInstansMedia().delete();
									MainActivity.isAirbus = 30;
								}
							}
							if(MainActivity.isAirbus==0) {
								if (str_zl.contains("单曲循环")) {
									if(str_zl.contains("取消")){
										MainActivity.playMode=0;
										MainActivity.playSound(5,"已为你取消单曲循环");
									}else{
										MainActivity.playMode=1;
										MainActivity.playSound(5,"已为你设置单曲循环");
									}
									MainActivity.isAirbus = 30;
								} else if (str_zl.contains("全部循环")) {
									if(str_zl.contains("取消")){
										MainActivity.playMode=0;
										MainActivity.playSound(5,"已为你取消全部循环");
									}else{
										MainActivity.playMode=2;
										MainActivity.playSound(5,"已为你设置全部循环");
									}
									MainActivity.isAirbus = 30;
								}
							}
						}
					}
					if (!MainActivity.musicIsSong) {
						String[] sleep = { "你滾","你找呗" ,"去休息","你去睡觉","走吧","走唄", "滾唄", "滾吧", "你休息","休息吧","休息唄","跪安","你下去","退下","闭嘴","沒事"};
						boolean pinyingFlag;
						for (String str: sleep) {
							pinyingFlag=(str_zl.contains(str))||PinYinComparison(pinying,
									str);
							if (pinyingFlag) {// 有识别词
								if((str.equals("你去睡觉"))||(str.equals("闭嘴"))) {
									if(MainActivity.musicTTsSt) {
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().pause();
										}
									}
									if(MainActivity.musicPlaySt) {
										if (MusicPlayMedia.getInstansMedia() != null) {
											MusicPlayMedia.getInstansMedia().pause();
										}
									}
								}
								if (MainActivity.mIsWakeUp ==255) {
									//MainActivity.activity.resetWakeup(false);
									MainActivity.mIsWakeUp = 0;
									MainActivity.activity.playGoodByeTheSleep("",false);
								}
								MainActivity.isAirbus = 30;
								bSearchFlag = 1;
								break;
							}
						}
					}else{
						if(str_zl.contains("我的收藏")||str_zl.contains("收藏的歌")){
							MainActivity.isAirbus = 30;
							List<SongPlayInfo> list= SongUitils.list;
							if(list!=null&&list.size()>0) {
								MusicPlayMedia.getInstansMedia().playURLList(list);
								MusicPlayMedia.getInstansMedia().setFileName(1,
										list.get(0).getPlayUrl(), 0);
								MusicPlayMedia.getInstansMedia().play();
							}else{
								MainActivity.playSound(5,"您当前没有收藏任何歌曲");
							}
						}
					}
				}
			}
		}
	}

	private boolean voiceInfoAction(String actStr,int nowPos,int randPos) {
		String uploadString;
		int ActFlag = 0;
		int timeValue;
		boolean isWork=false;
		boolean returnValue=false;
		int ifPos ;
		int thenPos ;
		int orPos ;
		String ifStringSource ="";
		String thenAct="";
		String orAct ="";
		uploadString = "";
		String ActionStr = actStr.replace("，", ",").replace("【", "[")
				.replace("［", "[").replace("］", "]").replace("】", "]");
		if(ActionStr.length()>0) {
			String[] ifWords = new String[3];
			String[] ActionFunction = {"假如", "然后", "或者","如果", "就", "否","if", "then", "else"};
			ifPos=0;
			thenPos=0;
			for (String str: ActionFunction) {
				if (ActionStr.contains(str)) {
					if((ifPos%3)==0){
						thenPos=1;
					}
					if(thenPos>0){
						ifWords[ActFlag]=str;
						ActFlag++;
						if(ActFlag>=3){
							break;
						}
					}
				}else{
					thenPos=0;
					ActFlag=0;
				}
				ifPos++;
			}
			returnValue=true;
			isWork=true;
			if (ActFlag == 3) {
				returnValue=false;
				ifPos = ActionStr.indexOf(ifWords[0]);
				thenPos = ActionStr.indexOf(ifWords[1]);
				orPos = ActionStr.indexOf(ifWords[2]);
				ifStringSource = ActionStr.substring(ifPos + ifWords[0].length(), thenPos);
				thenAct = ActionStr.substring(thenPos + ifWords[1].length(), orPos);
				orAct = ActionStr.substring(orPos + ifWords[2].length());
				boolean isIfAnd=false;
				if(ifStringSource.contains("+")){ //AND全部條件滿足
					isIfAnd=true;
					ifStringSource=ifStringSource.replace("+",",");
				}
				String[] ifArray=(ifStringSource+",").split(",");
				int ifAllState=0;
				int ifStateOk=0;
				int ifStateNo=0;
				for(String ifString:ifArray) {
					if(ifString.length()>0) {
						boolean isState=false;
						ifAllState++;
						timeValue = timeComprartion(1, 0, ifString);
						WeatherInfo info = WeatherUtils.getWeatherInfo();
						if (ifString.contains("温度")) {
							ActFlag=0;
							int resultVal=0;
							//室内温度大于25
							if(ifString.contains("室内")){
								ActFlag=1;
								resultVal=MainActivity.insideTemp[0];
							}else if(ifString.contains("室外")) {
								if (info != null) {
									ActFlag = 1;
									resultVal =info.getTemp();
								}else{
									isWork=false;
								}
							}else if(ifString.contains("客厅")){
								resultVal=MainActivity.insideTemp[1];
								ActFlag=1;
							}else if(ifString.contains("餐厅")){
								resultVal=MainActivity.insideTemp[2];
								ActFlag=1;
							}else if(ifString.contains("卧室")){
								resultVal=MainActivity.insideTemp[3];
								ActFlag=1;
							}else if(ifString.contains("父母房")){
								resultVal=MainActivity.insideTemp[4];
								ActFlag=1;
							}else if(ifString.contains("主人房")){
								resultVal=MainActivity.insideTemp[5];
								ActFlag=1;
							}else if(ifString.contains("儿童房")){
								resultVal=MainActivity.insideTemp[6];
								ActFlag=1;
							}
							if(ActFlag>0) {
								if (resultVal >= timeValue) {
									isState = true;
								}
								if (ifString.contains("小於") || ifString.contains("小于") || ifString.contains("<")) {
									isState = !isState;
								}
								if (isState) {
									ifStateOk++;
								} else {
									ifStateNo++;
								}
							}
						} else if (ifString.contains("湿度")) {
							ActFlag=0;
							int resultVal=0;
							if(ifString.contains("室内")){
								ActFlag=1;
								resultVal=MainActivity.Humidity[0];
							}else if(ifString.contains("室外")) {
								if ((info != null)&&(info.getHumidity().length()>0)) {
									ActFlag = 1;
									resultVal =Integer.parseInt(info.getHumidity().replace("%", ""));
								}else{
									isWork=false;
								}
							}else if(ifString.contains("客厅")){
								resultVal=MainActivity.Humidity[1];
								ActFlag=1;
							}else if(ifString.contains("餐厅")){
								resultVal=MainActivity.Humidity[2];
								ActFlag=1;
							}else if(ifString.contains("卧室")){
								resultVal=MainActivity.Humidity[3];
								ActFlag=1;
							}else if(ifString.contains("父母房")){
								resultVal=MainActivity.Humidity[4];
								ActFlag=1;
							}else if(ifString.contains("主人房")){
								resultVal=MainActivity.Humidity[5];
								ActFlag=1;
							}else if(ifString.contains("儿童房")){
								resultVal=MainActivity.Humidity[6];
								ActFlag=1;
							}
							if(ActFlag>0) {
								if (resultVal >= timeValue) {
									isState = true;
								}
								if (ifString.contains("小於") || ifString.contains("小于") || ifString.contains("<")) {
									isState = !isState;
								}
								if (isState) {
									ifStateOk++;
								} else {
									ifStateNo++;
								}
							}
						} else if (ifString.contains("PM25")) {
							ActFlag=0;
							int resultVal=0;
							if(ifString.contains("室内")){
								ActFlag=1;
								resultVal=MainActivity.pm25[0];
							}else if(ifString.contains("室外")) {
								if ((info != null)&&(info.getPm25().length()>0)) {
									ActFlag = 1;
									resultVal =Integer.parseInt(info.getPm25());
								}else{
									isWork=false;
								}
							}else if(ifString.contains("客厅")){
								resultVal=MainActivity.pm25[1];
								ActFlag=1;
							}else if(ifString.contains("餐厅")){
								resultVal=MainActivity.pm25[2];
								ActFlag=1;
							}else if(ifString.contains("卧室")){
								resultVal=MainActivity.pm25[3];
								ActFlag=1;
							}else if(ifString.contains("父母房")){
								resultVal=MainActivity.pm25[4];
								ActFlag=1;
							}else if(ifString.contains("主人房")){
								resultVal=MainActivity.pm25[5];
								ActFlag=1;
							}else if(ifString.contains("儿童房")){
								resultVal=MainActivity.pm25[6];
								ActFlag=1;
							}
							if(ActFlag>0) {
								if (resultVal >= timeValue) {
									isState = true;
								}
								if (ifString.contains("小於") || ifString.contains("小于") || ifString.contains("<")) {
									isState = !isState;
								}
								if (isState) {
									ifStateOk++;
								} else {
									ifStateNo++;
								}
							}
						} else if (ifString.contains("甲醛")) {
							ActFlag=0;
							int resultVal=0;
							if(ifString.contains("室内")){
								ActFlag=1;
								resultVal=MainActivity.formaldehyde[0];
							}else if(ifString.contains("室外")) {
								ActFlag=0;
								//
							}else if(ifString.contains("客厅")){
								resultVal=MainActivity.formaldehyde[1];
								ActFlag=1;
							}else if(ifString.contains("餐厅")){
								resultVal=MainActivity.formaldehyde[2];
								ActFlag=1;
							}else if(ifString.contains("卧室")){
								resultVal=MainActivity.formaldehyde[3];
								ActFlag=1;
							}else if(ifString.contains("父母房")){
								resultVal=MainActivity.formaldehyde[4];
								ActFlag=1;
							}else if(ifString.contains("主人房")){
								resultVal=MainActivity.formaldehyde[5];
								ActFlag=1;
							}else if(ifString.contains("儿童房")){
								resultVal=MainActivity.formaldehyde[6];
								ActFlag=1;
							}
							if(ActFlag>0) {
								if (resultVal >= timeValue) {
									isState = true;
								}
								if (ifString.contains("小於") || ifString.contains("小于") || ifString.contains("<")) {
									isState = !isState;
								}
								if (isState) {
									ifStateOk++;
								} else {
									ifStateNo++;
								}
							}
						} else if ((ifString.contains("照度"))||(ifString.contains("亮度"))) {
							ActFlag=0;
							int resultVal=0;
							if(ifString.contains("室内")){
								ActFlag=1;
								resultVal=MainActivity.illumination[0];
							}else if(ifString.contains("室外")) {
								ActFlag=0;
								//
							}else if(ifString.contains("客厅")){
								resultVal=MainActivity.illumination[1];
								ActFlag=1;
							}else if(ifString.contains("餐厅")){
								resultVal=MainActivity.illumination[2];
								ActFlag=1;
							}else if(ifString.contains("卧室")){
								resultVal=MainActivity.illumination[3];
								ActFlag=1;
							}else if(ifString.contains("父母房")){
								resultVal=MainActivity.illumination[4];
								ActFlag=1;
							}else if(ifString.contains("主人房")){
								resultVal=MainActivity.illumination[5];
								ActFlag=1;
							}else if(ifString.contains("儿童房")){
								resultVal=MainActivity.illumination[6];
								ActFlag=1;
							}
							if(ActFlag>0) {
								if (resultVal >= timeValue) {
									isState = true;
								}
								if (ifString.contains("小於") || ifString.contains("小于") || ifString.contains("<")) {
									isState = !isState;
								}
								if (isState) {
									ifStateOk++;
								} else {
									ifStateNo++;
								}
							}
						}else if ((ifString.contains("人員"))||(ifString.contains("人数"))) {
							if (MainActivity.NumberOfPeople >= timeValue) {
								isState=true;
							}
							if(ifString.contains("小於")||ifString.contains("小于")||ifString.contains("<")) {
								isState=!isState;
							}
							if (isState) {
								ifStateOk++;
							}else{
								ifStateNo++;
							}
						} else if (ifString.contains("空气质量")) {
							if ((info != null)&&(info.getAirQuality().length() > 0)) {
								if ((info.getAirQuality().contains("优")) || (info.getAirQuality().contains("良"))) {
									ifStateOk++;
								}else{
									ifStateNo++;
								}
							} else {
								isWork=false;
							}
						} else if (ifString.contains("室外下雨")) {
							if ((info != null)&&(info.getWeather().length() > 0)) {
								if (info.getWeather().contains("雨")) {
									ifStateOk++;
								}else{
									ifStateNo++;
								}
							}else {
								isWork=false;
							}
						} else if (ifString.contains("指定日期时间")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMddHHmm");
							if (ifString.contains(ReturnStr)) {
								ifStateOk++;
							}
						} else if (ifString.contains("指定日期")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMdd");
							if (ifString.contains(ReturnStr)) {
								ifStateOk++;
							}
						} else if (ifString.contains("指定某月")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMdd");
							Integer NowTime = Integer.valueOf(ReturnStr.substring(2, 4));
							if (NowTime == timeValue) {
								ifStateOk++;
							}
						} else if (ifString.contains("指定某日")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMdd");
							Integer NowTime = Integer.valueOf(ReturnStr.substring(4, 6));
							if (NowTime == timeValue) {
								ifStateOk++;
							}
						} else if (ifString.contains("指定某时")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMddHHmmss");
							Integer NowTime = Integer.valueOf(ReturnStr.substring(6, 8));
							if (NowTime == timeValue) {
								ifStateOk++;
							}
						} else if (ifString.contains("指定某分")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMddHHmmss");
							Integer NowTime = Integer.valueOf(ReturnStr.substring(8, 10));
							if (NowTime == timeValue) {
								ifStateOk++;
							}
						} else if (ifString.contains("指定星期")) {
							Calendar c = Calendar.getInstance();
							int mWay = Integer.parseInt(String.valueOf(c
									.get(Calendar.DAY_OF_WEEK)));
							String[] week={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
							if (ifString.contains(week[mWay-1])||((mWay==1)&&(ifString.contains("星期天")))) {
								ifStateOk++;
							}else{
								ifStateNo++;
							}
						} else if (ifString.contains("时间段")) {
							int start=ifString.indexOf("(");
							int end=ifString.indexOf(")");
							if((start!=-1)&&(end!=-1)&&(start<end)){
								String TimeLimit=ifString.substring(start+1,end);
								String[] periodArr = TimeLimit.split("--");
								if(periodArr.length==2) {
									if (checkPeriod(periodArr[0], periodArr[1])) {
										ifStateOk++;
									} else {
										ifStateNo++;
									}
								}
							}
						} else if (ifString.contains("时间")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMddHHmmss");
							Integer NowTime = Integer.valueOf(ReturnStr.substring(6, 8));
							if (NowTime >= timeValue) {
								isState=true;
							}
							if(ifString.contains("小於")||ifString.contains("小于")||ifString.contains("<")) {
								isState=!isState;
							}
							if (isState) {
								ifStateOk++;
							}else{
								ifStateNo++;
							}
						} else if (ifString.contains("分钟")) {
							String ReturnStr = dateToString(new Date(System.currentTimeMillis()), "yyMMddHHmmss");
							Integer NowTime = Integer.valueOf(ReturnStr.substring(8, 10));
							if (NowTime >= timeValue) {
								isState=true;
							}
							if(ifString.contains("小於")||ifString.contains("小于")||ifString.contains("<")) {
								isState=!isState;
							}
							if (isState) {
								ifStateOk++;
							}else{
								ifStateNo++;
							}
						}
						//else {
						//獲取所有設備作為條件值參考來源
						//}
					}
				}
				if(((isIfAnd)&&(ifAllState==ifStateOk))||((!isIfAnd)&&(ifStateOk>0))){
					ActionStr = thenAct + ",";
				}else{
					if(ifStateNo>0) {
						ActionStr = orAct + ",";
					}else{
						isWork=false;
					}
				}
			}else{
				if(nowPos!=randPos){
					isWork=false;
					returnValue=false;
				}
			}
		}
		if(isWork) {
			int StartPos = ActionStr.indexOf("[");
			int EndPos = ActionStr.indexOf("]");
			if ((StartPos >= 0 && EndPos > 0) && EndPos > StartPos) {
				uploadString = ActionStr.substring(StartPos + 1, EndPos);
				//MainActivity.activity.UploadText(uploadString,1);
				ActionStr = ActionStr.replace(uploadString, "").replace("[", ",")
						.replace("]", "");
			}
			String AllAction = DecodeinfoAction(ActionStr, 0,0);
			//if (AllAction.length() > 0) {
			//	ReturnAct += (",为你執行" + AllAction);
			//}
			MainActivity.playSound(5 , ReturnAct);
			if (!uploadString.equals("")) {
				//MainActivity.activity.UploadText(uploadString,1);
				DecodeinfoAction(uploadString, 1,0);
			}
		}
		return returnValue;
	}
	private String DecodeinfoAction(String ActionStr,int cType,int source) {
		//cType=0 文本   cType=1 家居控制
		int ActFlag ;
		int timeValue;
		String AllAction = ActionStr + ",";
		String[] ActFun = AllAction.split(",");
		AllAction="";
		for (String str: ActFun) {
			if (str.length() > 0) {
				boolean cFlag=true;
				if (str.contains("时间段")) {
					int start = str.indexOf("(");
					int end = str.indexOf(")");
					if ((start != -1) && (end != -1) && (start < end)) {
						String TimeLimit = str.substring(start + 1, end);
						String[] periodArr = TimeLimit.split("--");
						if (periodArr.length == 2) {
							cFlag=checkPeriod(periodArr[0], periodArr[1]);
						}
					}
				}
				if(cFlag) {
					for (ActFlag = 0; ActFlag < 20; ActFlag++) {
						if (voiceInfoTime[ActFlag] == 0) {
							break;
						}
					}
					if (ActFlag < 20) {
						if (str.contains("TTS")) {
							voiceType[ActFlag] = 2;
						} else if (str.contains("URL")) {
							voiceType[ActFlag] = 3;
						} else if (str.contains("SD")) {
							voiceType[ActFlag] = 4;
						} else if (str.contains("ASK")) {
							//不允許自問答再調用自問答
							voiceType[ActFlag] = (source == 1) ? 5 : 255;
						} else {
							voiceType[ActFlag] = cType; //0 or 1
						}
						if (voiceType[ActFlag] < 255) {
							//ReturnAct += ",同时为你執行";
							int delayPos = str.indexOf("#");
							if (delayPos != -1) {
								timeValue = timeComprartion(1, delayPos, str);
								if (str.substring(delayPos).contains("分钟")) {
									if (timeValue > 1000) {
										timeValue = 1000;
									}
									voiceInfoTime[ActFlag] = timeValue * 60;
								} else if (str.substring(delayPos).contains("小时")) {
									if (timeValue > 12) {
										timeValue = 12;
									}
									voiceInfoTime[ActFlag] = timeValue * 3600;
								} else {
									voiceInfoTime[ActFlag] = timeValue;
								}
								voiceInfoStr[ActFlag] = str
										.substring(0, delayPos);
								AllAction += (timeValue + "秒後" + voiceInfoStr[ActFlag]);
							} else {
								voiceInfoTime[ActFlag] = 1;    //(cType==0)?2:1;	//1
								voiceInfoStr[ActFlag] = str;
								AllAction += voiceInfoStr[ActFlag];
							}
						}
					}
				}
			}
		}
		return AllAction;
	}

	private void sendTVCmd(String tv_set) {
		List<Device> list= DeviceFactory.getDeviceByAction(deviceModelParam.getRoomId(),5,0,0);
		if(list.size()>0) {
			Device tvModel=list.get(0);
			String deviceID=deviceModelParam.getDeviceID();
			if(deviceID!=null&&!deviceID.equals("000000")) {
				int len=Integer.parseInt(deviceID.substring(0,1));
				if(len<4) {
					String cmd;
					String Hex_pram = "";
					String channelID = deviceID.substring(1, (1 + len));
					/*
					if(modelflag > 0){
						Hex_pram = "000" + channelID;
						Hex_pram = "C" + Hex_pram.substring(Hex_pram.length() - 3);
						if (modelflag == 1) {
							cmd = "*M81" + modecode + modetime + modeIo + tvModel.getProductsCode() + tvModel.getDeviceID() + Hex_pram + modeSthh + modeStmm + modeEndhh + modeEndmm + modeMonth;
							isSendMode = true;
							if(ModeGateMac.length()>0) {
								sendToCurrtneGaway
										(ModeGateType,ModeGateMac,cmd);
								return;
							}
						} else {
							cmd = "*I00" + toHex(randomKey) + "FF" + modeIo + "248" + (modelflag - 1)
									+ tvModel.getProductsCode() + tvModel.getDeviceID() + Hex_pram + modeSthh + modeStmm + modeEndhh
									+ modeEndmm + modetime;
							randomKey++;
							if (randomKey >= 256) {
								randomKey = 0;
							}
						}
					}else {
					*/
                    Hex_pram="";
                    for (int i = 0; i < len; i++) {
                        Hex_pram = Hex_pram + "0" + channelID.substring(i, i + 1);
                    }
                    Hex_pram+="000000";
                    cmd = "*C0019FA" + tvModel.getProductsCode() + tvModel.getDeviceID() + "C" + len + Hex_pram.substring(0,6);
                    TcpSender.sendMssageAF(0,cmd);
					//}
				}
			}
		}
	}

	private void initDevie(String networds, int modelflag) {

		int iPos = 0;
		int iPosAct = 255;
		int iVqonPos;
		int timeVal = 0;
		boolean MainOption = true;
		boolean SubOption = true;
		// String[] _device_Info;
		String string_sw_prams = "00";
		iVqonPos = networds.length();
		deviceValue = Integer.parseInt(deviceProductCode, 16);
		String CheckAct = networds.replace(words_ls,"").replace(spaceNameStr, "");
		String action = "";
		// spaceNameStr = "";
		/*
		 * if (deviceValue == type_window) { // 使用內建1527发碼 if
		 * (devieID.equals("00") && devieMid1.equals("00") &&
		 * devieMid2.equals("00")) { if (networds.indexOf("窗帘") != -1) {
		 * SendType = "A0"; } if (networds.indexOf("紗窗") != -1) { SendType =
		 * "A1"; } } }
		 */
		// if((deviceValue>=80 &&
		// deviceValue<=100)||(deviceValue==33)||MuteFlag){
		if ((deviceValue >= 80 && deviceValue <= 100) || (deviceValue == 33)) {
			// 电视&背景音乐
			//if (MainOption) {
			// String[] mute = { "关闭静音", "静音关闭", "静音关", "取消静音", "静音取消",
			// "关静音",
			// "取消" };
			String[] mute = MainActivity.activity.getResources()
					.getStringArray(R.array.closeMutes);
			for (String str: mute) {
				if (networds.contains(str)) {// 有识别词
					iPos = networds.indexOf(str);
					if (iPos < iVqonPos) {
						ReturnAct = ReturnAct + "已设定" + str;
						ActionFlag = 1;
						if (deviceValue >= 80 && deviceValue <= 100) {// 电视
							deviceCmd = "*SA0" + deviceProductCode + "00"
									+ devieID + "0F";
							ActionFlag = 2;
						} else if (deviceValue == 33) {
							deviceCmd = "*S21" + deviceProductCode + "00"
									+ devieID + "00";
						}
						sendMssageAF(modelflag, deviceCmd);
						MainOption = false;
						break;
					}
				}
			}
			//}
			if (MainOption) {
				// String[] mute = { "打开静音", "静音", "开启静音", "静音打开", "静音开启",
				// "静音开",
				// "静音" };
				String[] muteCnace = MainActivity.activity.getResources()
						.getStringArray(R.array.Openmutes);
				for (String str: muteCnace) {
					if (networds.contains(str)) {// 有识别词
						iPos = networds.indexOf(str);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + "已设定" + str;
							ActionFlag = 1;
							if (deviceValue >= 80 && deviceValue <= 100) { // 电视
								deviceCmd = "*SA0" + deviceProductCode + "00"
										+ devieID + "0F";
								ActionFlag = 2;
							} else if (deviceValue == 33) { // 背景音乐
								deviceCmd = "*S11" + deviceProductCode + "00"
										+ devieID + "00";
							}
							sendMssageAF(modelflag, deviceCmd);
							MainOption = false;
							break;
						}
					}
				}
			}
		}
		// if(((deviceValue==33))&&(MainOption==true)||PlayFalg){ //背景音乐
		if (((deviceValue == 33)) && (MainOption)) { // 背景音乐
			// String[] play = { "播放", "播放打开", "播放开始", "播放开启", "打开播放", "开启播放",
			// "开始播放", "暂停", "暂停播放", "取消播放", "停止", "停止播放", "播放停止" };
			String[] play = MainActivity.activity.getResources()
					.getStringArray(R.array.playSet);
			for (int i = 0; i < play.length; i++) {
				if (networds.contains(play[i])) {// 有识别词
					iPos = networds.indexOf(play[i]);
					if (iPos < iVqonPos) {
						ReturnAct = ReturnAct + "已设定" + play[i];
						String actionPlay = "*S13";
						if (i < 7) {
							actionPlay = "*S22";
						} else if (i < 9) {
							actionPlay = "*S12";
						}
						deviceCmd = actionPlay + deviceProductCode + "00"
								+ devieID + "00";
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						MainOption = false;
						break;
					}
				}
			}
		}
		if (((deviceValue == type_window)) && (MainOption)) { // Windows
			String[] puase = { "停止", "暂停", "停", "STOP", "stop", "好了", "够了",
					"可以了" };
			for (String str: puase) {
				if (networds.contains(str)) {// 有识别词
					ReturnAct = ReturnAct + "已设定" + str;
					if (deviceIO.equals("1")) {
						deviceCmd = "*S54" + deviceProductCode + "00" + devieID
								+ "FF";
					} else {
						deviceCmd = "*S51" + deviceProductCode + "00" + devieID
								+ "FF";
					}
					sendMssageAF(modelflag, deviceCmd);
					ActionFlag = 1;
					MainOption = false;
					break;
				}
			}
			if (MainOption) {
				String[] editMode = { "配对学习", "配对删除" };
				for (int i = 0; i < editMode.length; i++) {
					if (networds.contains(editMode[i])) {// 有识别词
						if (i == 0) {
							deviceCmd = "*SC0" + deviceProductCode + "00"
									+ devieID + "00";
						} else {
							deviceCmd = "*SB0" + deviceProductCode + "00"
									+ devieID + "00";
						}
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 2;
						MainOption = false;
						break;
					}
				}
			}
		}
		if ((deviceValue == 30)
				&& (MainOption)) { // 調光
			if (!deviceProductCode.equals("03")) {
				// String[] LedColor = { "蓝", "蓝色", "蓝色光", "蓝光", "红", "红色",
				// "红色光",
				// "红光", "绿", "绿色", "绿光", "绿色光", "白", "白色", "白光", "白色光",
				// "紫", "紫色", "紫色光", "紫光", "橙", "橙色光", "橙色", "橙光", "黄色光",
				// "黄色", "黄", "黄光", "粉色光", "粉色", "粉红", "粉红色", "场景",
				// "场景模式", "情景", "情景模式", "自动", "自动变色", "自动变" };
				String[] LedColor = MainActivity.activity
						.getResources().getStringArray(R.array.ledColor);
				for (int i = 0; i < LedColor.length; i++) {
					if (networds.contains(LedColor[i])) {// 有识别词
						int cIndex = i;
						switch (i) {
							case 0:
							case 1:
							case 2:
							case 3:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "10";
								cIndex = 1;
								break;
							case 4:
							case 5:
							case 6:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "B0";
								cIndex = 6;
								break;
							case 7:
							case 8:
							case 9:
							case 10:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "60";
								cIndex = 10;
								break;
							case 11:
							case 12:
							case 13:
							case 14:
								deviceCmd = "*SAA" + deviceProductCode + "00"
										+ devieID + "0" + deviceIO;
								cIndex = 14;
								break;
							case 15:
							case 16:
							case 17:
							case 18:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "F0";
								cIndex = 18;
								break;
							case 19:
							case 20:
							case 21:
							case 22:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "98";
								cIndex = 22;
								break;
							case 23:
							case 24:
							case 25:
							case 26:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "80";
								cIndex = 26;
								break;
							case 27:
							case 28:
							case 29:
							case 30:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "C8";
								cIndex = 30;
								break;
							case 31:
							case 32:// 暖色，暖光
								deviceCmd = "*SAA" + deviceProductCode + "00"
										+ devieID + "1" + deviceIO;
								cIndex = 32;
								break;
							case 33:
								deviceCmd = "*SAA" + deviceProductCode + "00"
										+ devieID + "2" + deviceIO;
								cIndex = 33;
								break;
							case 34:
								deviceCmd = "*SA" + deviceIO + deviceProductCode
										+ "00" + devieID + "40";
								cIndex = 34;
								break;
							case 35:
								deviceCmd = "*SAA" + deviceProductCode + "00"
										+ devieID + "4" + deviceIO;
								cIndex = 35;
								break;
							case 36:
							case 37:
							case 38:
							case 39:
							case 40:
							case 41:
							case 42:
							case 43:
							case 44:
								cIndex = (i - 35);
								deviceCmd = "*SAE" + deviceProductCode + "00"
										+ devieID + cIndex + deviceIO;
								cIndex = i;
								break;
							default:
								deviceCmd = "*SAE" + deviceProductCode + "00"
										+ devieID + "0" + deviceIO;
								break;
						}
						ReturnAct = ReturnAct + "已设定" + LedColor[cIndex];

						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						timeVal = timeComprartion(0, iPos, CheckAct);
						if (timeVal > 0) {
							string_sw_prams = toHex(timeVal);
							deviceCmd = "*S5" + deviceIO + deviceProductCode
									+ "00" + devieID + string_sw_prams;
							sendMssageAF(modelflag, deviceCmd);
							ActionFlag = 1;
						}
						MainOption = false;
						break;
					}
				}
				// String[] LedAlarm = { "报警", "警报", "闪烁" };
				String[] LedAlarm = MainActivity.activity
						.getResources().getStringArray(R.array.LedAlarm);
				for (String str: LedAlarm) {
					if (networds.contains(str)) {// 有识别词
						ReturnAct = ReturnAct + "已设定" + str;
						deviceCmd = "*SA9" + deviceProductCode + "00" + devieID
								+ "0" + deviceIO;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						MainOption = false;
						break;
					}
				}
			}
			// String[] LedSpeed = { "速度快", "速度加", "速度快一点", "速度慢", "速度减",
			// "速度慢一点" };
			String[] LedSpeed = MainActivity.activity
					.getResources().getStringArray(R.array.speed);
			for (int i = 0; i < LedSpeed.length; i++) {
				if (networds.contains(LedSpeed[i])) {// 有识别词
					ReturnAct = ReturnAct + "已" + LedSpeed[i];
					deviceCmd = "*SAD" + deviceProductCode + "00" + devieID
							+ ((i < 3) ? "FA" : "FB");
					sendMssageAF(modelflag, deviceCmd);
					ActionFlag = 1;
					SubOption = false;
					break;
				}
			}
			// String[] DimmerSpeed = { "速度正常", "高速", "中速", "低速" };
			String[] DimmerSpeed = MainActivity.activity
					.getResources().getStringArray(R.array.ledSpeed);
			for (int i = 0; i < DimmerSpeed.length; i++) {
				if (networds.contains(DimmerSpeed[i])) {// 有识别词
					ReturnAct = ReturnAct + "已" + DimmerSpeed[i];
					switch(i){
						case 0:string_sw_prams = toHex(80);
							break;
						case 1:string_sw_prams = toHex(0);
							break;
						case 2:string_sw_prams = toHex(50);
							break;
						case 3:string_sw_prams = toHex(100);
							break;
					}
					deviceCmd = "*SAD" + deviceProductCode + "00" + devieID
							+ string_sw_prams;
					sendMssageAF(modelflag, deviceCmd);
					ActionFlag = 1;
					SubOption = false;
					break;
				}
			}
			if(SubOption){
				if (networds.contains("速度")) {// 有识别词
					timeVal = timeComprartion(1, 0, CheckAct);
					if ((timeVal >= 0) && (timeVal <= 100)) {
						string_sw_prams = toHex(timeVal);
						deviceCmd = "*SAD" + deviceProductCode + "00" + devieID
								+ string_sw_prams;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
					}
				}
			}
			String[] dimer = MainActivity.activity.getResources()
					.getStringArray(R.array.dimmer);
			for (int i = 0; i < dimer.length; i++) {
				if (networds.contains(dimer[i])) {// 有识别词
					ReturnAct = ReturnAct + "已设定" + dimer[i];
					if (i < 11) {
						deviceCmd = "*S8" + deviceIO + deviceProductCode + "00"
								+ devieID + "00";
					} else if (i < 23) {
						deviceCmd = "*S7" + deviceIO + deviceProductCode + "00"
								+ devieID + "00";
					} else if (i < 28) {
						deviceCmd = "*S7" + deviceIO + deviceProductCode + "00"
								+ devieID + "64";
					} else {
						deviceCmd = "*S7" + deviceIO + deviceProductCode + "00"
								+ devieID + "0F";
					}
					sendMssageAF(modelflag, deviceCmd);
					ActionFlag = 1;
					break;
					// }
				}
			}
		}
		if (deviceValue == 8||deviceValue == 6) { // 时序开关
			if (MainOption) {
				String[] sw_open_no = { "打开时序1路", "*SA1", "打开时序2路", "*SA2",
						"打开时序3路", "*SA3", "打开时序4路", "*SA4", "打开时序5路", "*SA5",
						"打开时序6路", "*SA6", "打开时序7路", "*SA7", "打开时序8路", "*SA8" ,"打开断路器1路", "*SA1", "打开断路器2路", "*SA2",
						"打开断路器3路", "*SA3", "打开断路器4路", "*SA4", "打开断路器5路", "*SA5",
						"打开断路器6路", "*SA6", "打开断路器7路", "*SA7", "打开断路器8路", "*SA8"};
				// String[] sw_open_no = (String[]) MainActivity.activity
				// .getResources().getStringArray(R.array.sw_open);
				for (int i = 0; i < sw_open_no.length; i += 2) {
					if (networds.contains(sw_open_no[i])) {// 有识别词
						deviceCmd = sw_open_no[i + 1] + deviceProductCode
								+ "00" + devieID + "01";
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						MainOption = false;
						break;
					}
				}
			}
			if (MainOption) {
				String[] sw_open_no = { "关闭时序1路", "*SA1", "关闭时序2路", "*SA2",
						"关闭时序3路", "*SA3", "关闭时序4路", "*SA4", "关闭时序5路", "*SA5",
						"关闭时序6路", "*SA6", "关闭时序7路", "*SA7", "关闭时序8路", "*SA8","关闭断路器1路", "*SA1", "关闭断路器2路", "*SA2",
						"关闭断路器3路", "*SA3", "关闭断路器4路", "*SA4", "关闭断路器5路", "*SA5",
						"关闭断路器6路", "*SA6", "关闭断路器7路", "*SA7", "关闭断路器8路", "*SA8"  };
				// String[] sw_open_no = (String[]) MainActivity.activity				// .getResources().getStringArray(R.array.sw_open);

				for (int i = 0; i < sw_open_no.length; i += 2) {
					if (networds.contains(sw_open_no[i])) {// 有识别词
						deviceCmd = sw_open_no[i + 1] + deviceProductCode
								+ "00" + devieID + "00";
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						MainOption = false;
						break;
					}
				}
			}
		}
		if((deviceValue>101)&&(deviceValue<=112)) {
			if (MainOption) {
				String[] singal = {"信号源1","信号源2","信号源3","信号源4"};
				for (int i = 0; i < singal.length;i++){
					if (networds.contains(singal[i])) {// 有识别词
						deviceCmd =  "*SA4"+ deviceProductCode+ "00"+devieID+"0"+(i+1);
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						MainOption = false;
					}
				}
			}

		}
		Boolean IsOnFlag=false;
		Boolean IsOffFlag=false;
		Boolean IsTimeFlag=false;
		if (MultiFlag > 1) {
			if(MainOption){
				//				// 從數據庫獲取
				String[] sw_open_no = { "打开", "开启", "开起", "开灯", "开去", "启动",
						"开", "ON", "on", "OPEN", "open", "START", "start",
						"关闭", "关", "观", "CLOSE", "close", "OFF", "off", "关窗",
						"关机" };
				iVqonPos=networds.length();
				for (int i = (cStartPos + words_ls.length()); i < iVqonPos; i++) {
					for (int j = 0; j < sw_open_no.length; j++) {
						iPos = 1;
						for (int k = 0; k < sw_open_no[j].length(); k++) {
							if ((i + k) >= networds.length()) {
								break;
							}
							String getOneStr1 = networds.substring(i + k, i + k
									+ 1);
							String getOneStr2 = sw_open_no[j].substring(k,
									k + 1);
							if (!getOneStr1.equals(getOneStr2)) {
								iPos = 0;
								break;
							}
						}
						if (iPos == 1) {
							iPosAct = j;
							if(j<13){
								IsOnFlag = true;
							}else{
								IsOffFlag=true;
							}
							MainOption=false;
							action=sw_open_no[iPosAct];
							iPos = cStartPos + words_ls.length(); // s.length());
							if (iPos == 0) {
								iPos = networds.indexOf(action);
							}
							timeVal = timeComprartion(0, 0, CheckAct);
							break;
						}
					}
					if (iPosAct < 255) {
						break;
					}
				}
			}
		}else{
			if (MainOption) {
				//				// On
				// 從數據庫獲取
				// String[] sw_open_no = { "打开", "开启", "开起", "开灯", "开去", "启动",
				// "开",
				// "ON", "on", "OPEN", "open", "START", "start" };
				timeVal = timeComprartion(0, 0, CheckAct);
				String[] sw_open_no = MainActivity.activity
						.getResources().getStringArray(R.array.sw_open);
				for (int i = 0; i < sw_open_no.length; i++) {
					boolean pinyingFlag = false;
					if (CheckAct.contains(sw_open_no[i])) {
						pinyingFlag = true;
					} else {
						String pinying= getPinYin(CheckAct);
						String pinyingDev = getPinYin(sw_open_no[i]);
						if ((pinying.length() > 0)
								&& (pinyingDev.length() > 0)) {
							if (pinying.equals(pinyingDev)) {
								pinyingFlag = true;
							}
						}
					}
					//if (CheckAct.contains(sw_open_no[i])) {// 有识别词
					if (pinyingFlag){
						iPosAct = i;
						IsOnFlag = true;
						MainOption=false;
						action=sw_open_no[iPosAct];
						//IsTimeFlag=yes;
						timeVal = timeComprartion(0, 0, CheckAct);
						if(timeVal>0){
							if(getCharCount(CheckAct,"后")==1){
								IsTimeFlag=true;
							}
						}
						break;
					}
				}
			}
			if (MainOption) {
				// Off
				// String[] sw_open_no = { "关闭", "关", "观", "CLOSE", "close",
				// "OFF",
				// "off", "关窗", "关机" };
				String[] sw_open_no = MainActivity.activity
						.getResources().getStringArray(R.array.sw_close);
				for (int i = 0; i < sw_open_no.length; i++) {
					boolean pinyingFlag = false;
					if (CheckAct.contains(sw_open_no[i])) {
						pinyingFlag = true;
					} else {
						String pinying= getPinYin(CheckAct);
						String pinyingDev = getPinYin(sw_open_no[i]);
						if ((pinying.length() > 0)
								&& (pinyingDev.length() > 0)) {
							if (pinying.equals(pinyingDev)) {
								pinyingFlag = true;
							}
						}
					}
					//if (CheckAct.contains(sw_open_no[i])) {// 有识别词
					if (pinyingFlag){
						iPosAct = i;
						IsOffFlag=true;
						MainOption=false;
						action=sw_open_no[iPosAct];
						//IsTimeFlag=yes;
						timeVal = timeComprartion(0, 0, CheckAct);
						if(timeVal>0){
							if(getCharCount(CheckAct,"后")==1){
								IsTimeFlag=true;
							}
						}
						break;
					}
				}
			}
		}
		if(IsOnFlag){
			// 獲取回碼指令
			if (IsTimeFlag) {
				ReturnAct = ReturnAct + timeReturn + "后" + action;
			}else {
				ReturnAct = ReturnAct + "已" + action + (timeReturn.length()>0?(timeReturn +"后关闭"):"");
			}
			// 獲取時間參數
			if (timeVal > 0) {
				string_sw_prams = toHex(timeVal);
				if(IsTimeFlag){
					action = "*S4" + deviceIO;
				}else{
					action = "*S5" + deviceIO;
				}
			} else {
				action = "*S2" + deviceIO;
				string_sw_prams = "00";
			}

			deviceCmd = action + deviceProductCode + "00" + devieID
					+ string_sw_prams;
			sendMssageAF(modelflag, deviceCmd);
			ActionFlag = 1;
			if((deviceValue>101)&&(deviceValue<=112)) {
				CheckTouYingjiDevice("打开", modelflag);
			}
			//MainOption = false;
		}
		if(IsOffFlag){
			// 獲取回碼指令
			if (IsTimeFlag) {
				ReturnAct = ReturnAct + timeReturn + "后" + action;
			}else {
				ReturnAct = ReturnAct + "已" + action + (timeReturn.length()>0?(timeReturn +"后打开"):"");
			}
			if (timeVal > 0) {
				string_sw_prams = toHex(timeVal);
				if(IsTimeFlag){
					action = "*S3" + deviceIO;
				}else{
					action = "*S6" + deviceIO;
				}
			} else {
				action = "*S1" + deviceIO;
				string_sw_prams = "00";
			}
			deviceCmd = action + deviceProductCode + "00" + devieID
					+ string_sw_prams;
			sendMssageAF(modelflag, deviceCmd);
			if (deviceValue>101 && deviceValue<=112) {//投影机
				//1804
				CheckTouYingjiDevice("关闭", modelflag);
			}
			ActionFlag = 1;
			//MainOption = false;
		}
		if (deviceValue == 12) { // 窗簾
			String[] openAngle = (String[]) MainActivity.activity.getResources().getStringArray(R.array.openAngle);
			int angle;
			for (angle = 0; angle < openAngle.length; angle++) {
				if (networds.contains(openAngle[angle])) {// 有识别词
					ReturnAct = ReturnAct + MainActivity.activity.getString(R.string.alredy)+ openAngle[angle];
					break;
				}
			}
			//joe test
			string_sw_prams = "FF";
			if (angle < openAngle.length) {
				if (angle > 5) {
					angle = angle - 5;
				}
				if (angle == 5) {
					angle = 2;
				}
				string_sw_prams = toHex(angle);
				action = "*SA0";
				deviceCmd = action + deviceProductCode + "00" + devieID
						+ string_sw_prams;
				sendMssageAF(modelflag, deviceCmd);
				ActionFlag = 1;
			}
		}
		if (deviceValue >= 48 && deviceValue < 80) {// 空调
			// mode
			//if (SubOption) {
			String[] air = { "自冷", "02", "制冷", "02", "制冷模式", "02", "冷气",
					"02", "智能模式", "02", "智能", "02", "加热", "04", "制热", "04",
					"制热模式", "04", "炙热", "04", "送风", "05", "送风模式", "05",
					"出风", "05", "除湿", "03", "抽湿", "03", "厨师", "03", "自动",
					"01", "自动模式", "01", "制动", "01" };

			// String[] air = (String[])
			// MainActivity.activity.getResources()
			// .getStringArray(R.array.airMode);
			for (int i = 0; i < air.length; i += 2) {
				if (networds.contains(air[i])) {// 有识别词
					iPos = networds.indexOf(air[i]);
					if (iPos < iVqonPos) {
						ReturnAct = ReturnAct + "已设定" + air[i];
						string_sw_prams = air[i + 1];
						deviceCmd = "*SA4" + deviceProductCode + "00"
								+ devieID + string_sw_prams;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						//SubOption = false;
						break;
					}
				}
			}
			//}

			//SubOption = true;
			// fan
			//if (SubOption) {
			String[] airfan = { "风量高速", "04", "高速", "04", "高", "04",
					"风量中速", "03", "中速", "03", "中", "03", "风量低速", "02",
					"低速", "02", "低", "02" };
			for (int i = 0; i < airfan.length; i += 2) {
				if (networds.contains(airfan[i])) {// 有识别词
					iPos = networds.indexOf(airfan[i]);
					if (iPos < iVqonPos) {
						ReturnAct = ReturnAct + "已设定" + airfan[i];
						string_sw_prams = airfan[i + 1];
						deviceCmd = "*SA5" + deviceProductCode + "00"
								+ devieID + string_sw_prams;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						//SubOption = false;
						break;
					}
				}
			}
			//}
			SubOption = true;
			// Set Temp
			//if (SubOption) {
			String[] airTemp = { "太冷", "0A", "太冷了", "0A", "太低", "0A",
					"太低了", "0A", "温度太低", "0A", "温度太低了", "0A", "温度太冷", "0A",
					"温度太冷了", "0A", "太热", "04", "太热了", "04", "太高", "04",
					"温度太高", "04", "太高了", "04", "温度太高了", "04", "温度太热", "04",
					"温度太热了", "04", "温度最高", "0D", "温度最大", "0D", "最大温度",
					"0D", "最高温度", "0D", "最大", "0D", "最高", "0D", "最小温度",
					"01", "最低温度", "01", "最小", "01", "最低", "01", "温度最低",
					"01", "温度最小", "01" };
			for (int i = 0; i < airTemp.length; i += 2) {
				if (networds.contains(airTemp[i])) {// 有识别词
					iPos = networds.indexOf(airTemp[i]);
					if (iPos < iVqonPos) {
						// ReturnAct = ReturnAct + "已" + airTemp[i];
						if (i < 14) {
							ReturnAct = ReturnAct + "已设定27度";
						} else if (i < 30) {
							ReturnAct = ReturnAct + "已设定21度";
						} else if (i < 42) {
							ReturnAct = ReturnAct + "已设定30度";
						} else {
							ReturnAct = ReturnAct + "已设定18度";
						}
						string_sw_prams = airTemp[i + 1];
						deviceCmd = "*SA2" + deviceProductCode + "00"
								+ devieID + string_sw_prams;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
						SubOption = false;
						break;
					}
				}
			}
			//}
			// airOne
			if (SubOption) {
				String[] airOne = { "温度加一", "*SA2", "温度高一点", "*SA2", "温度高点",
						"*SA2", "高一点", "*SA2", "升一点", "*SA2", "调高一点", "*SA2",
						"温度上升", "*SA2", "上升", "*SA2", "再高一点", "*SA2", "温度减一",
						"*SA3", "温度低一点", "*SA3", "温度低点", "*SA3", "低一点", "*SA3",
						"降一点", "*SA3", "第一点", "*SA3", "调低一点", "*SA3", "温度下降",
						"*SA3", "下降", "*SA3", "再低一点", "*SA3" };
				for (int i = 0; i < airOne.length; i += 2) {
					if (networds.contains(airOne[i])) {// 有识别词
						iPos = networds.indexOf(airOne[i]);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + "已设定" + airOne[i];
							deviceCmd = airOne[i + 1] + deviceProductCode
									+ "00" + devieID + "00";
							sendMssageAF(modelflag, deviceCmd);
							ActionFlag = 1;
							SubOption = false;
							break;
						}
					}
				}
			}
			if (SubOption && (timeVal == 0)) { // 温度
				timeVal = timeComprartion(1, 0, CheckAct);
				if (timeVal > 0) {
					if (timeVal < 6) {
						//if (SubOption) {
						String[] AddSub = { "加", "*SA9", "升", "*SA9", "生",
								"*SA9", "昇", "*SA9", "减", "*SAA", "降",
								"*SAA", "将", "*SAA" };
						for (int i = 0; i < AddSub.length; i += 2) {
							if (networds.contains(AddSub[i])) {// 有识别词
								ReturnAct = ReturnAct + "已设定" + AddSub[i] + timeVal +"度";
								string_sw_prams = toHex(timeVal);
								deviceCmd = AddSub[i + 1]
										+ deviceProductCode + "00"
										+ devieID + string_sw_prams;
								sendMssageAF(modelflag, deviceCmd);
								ActionFlag = 1;
								SubOption = false;
								break;
							}
						}
						//}
					} else if ((timeVal > 17) && (timeVal < 31)) {// Set temp
						ReturnAct = ReturnAct + timeReturn +"度";
						//timeVal = (timeVal - 17);
						string_sw_prams = toHex(timeVal);
						deviceCmd = "*SA2" + deviceProductCode + "00" + devieID
								+ string_sw_prams;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
					}
				}
			}
		}
		// else if((deviceValue>=80 &&
		// deviceValue<=100)||(deviceValue==33)||VolumFlag){ //电视&背景音乐
		else if ((deviceValue >= 80 && deviceValue <= 100)
				|| (deviceValue == 33)) { // 电视&背景音乐
			// 音量
			//if (SubOption) {
			String[] volAdd = { "音量加", "声音大", "音量大", "声音大一点", "音量大一点",
					"声音太小了", "高一点", "音量加一点", "再加一点", "再大一点", "大一点", "太小了" };
			for (String str: volAdd) {
				if (networds.contains(str)) {// 有识别词
					iPos = networds.indexOf(str);
					if (iPos < iVqonPos) {
						ReturnAct = ReturnAct + "已设定" + str;
						ActionFlag = 1;
						if (deviceValue >= 80 && deviceValue <= 100) {
							deviceCmd = "*SA0" + deviceProductCode + "00"
									+ devieID + "0B";
							if ((timeVal == 0) && (modelflag == 0)) {
								timeVal = timeComprartion(1, 0, CheckAct);
								if (timeVal > 1 && timeVal < 10) {
									for (int j = 1; j < timeVal; j++) {
										sendMssageAF(0, deviceCmd);
									}
								}
							}
							MainActivity.playSound(2, ReturnAct);
							ActionFlag = 2;
						} else if (deviceValue == 33) {
							deviceCmd = "*SA2" + deviceProductCode + "00"
									+ devieID + "00";
						}
						sendMssageAF(modelflag, deviceCmd);
						SubOption = false;
						break;
					}
				}
			}
			//}
			if (SubOption) {
				String[] volSub = { "音量小", "声音小", "声音小一点", "音量小一点", "声音太大了",
						"低一点", "音量减", "再小一点", "小一点", "音量太大了", "减一点", "太大了",
						"音量在大了", "音量键" };
				for (String str:volSub) {
					if (networds.contains(str)) {// 有识别词
						iPos = networds.indexOf(str);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + "已设定" + str;
							ActionFlag = 1;
							if (deviceValue >= 80 && deviceValue <= 100) {
								deviceCmd = "*SA0" + deviceProductCode + "00"
										+ devieID + "0C";
								if ((timeVal == 0) && (modelflag == 0)) {
									timeVal = timeComprartion(1, 0, CheckAct);
									if (timeVal > 1 && timeVal < 10) {
										for (int j = 1; j < timeVal; j++) {
											sendMssageAF(0, deviceCmd);
										}
									}
								}
								MainActivity.playSound(2, ReturnAct);
								ActionFlag = 2;
							} else if (deviceValue == 33) {
								deviceCmd = "*SA3" + deviceProductCode + "00"
										+ devieID + "00";
							}
							sendMssageAF(modelflag, deviceCmd);
							SubOption = false;
							break;
						}
					}
				}
			}
			if (deviceValue >= 80 && deviceValue <= 100) {
				// 頻道
				//SubOption = true;
				//if (SubOption) {
				String[] ch = { "频道加", "0D", "贫道加", "0D", "平道加", "0D",
						"平到家", "0D", "下一台", "0D", "加一台", "0D", "频道减", "0E",
						"频道假", "0E", "频道几", "0E", "贫道戒", "0E", "频道几", "0E",
						"上一台", "0E", "平道减", "0E", "平到减", "0E", "减一台", "0E" };
				for (int i = 0; i < ch.length; i += 2) {
					if (networds.contains(ch[i])) {// 有识别词
						iPos = networds.indexOf(ch[i]);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + "已设定" + ch[i];
							deviceCmd = "*SA0" + deviceProductCode + "00"
									+ devieID + ch[i + 1];
							sendMssageAF(modelflag, deviceCmd);
							MainActivity.playSound(2, ReturnAct);
							ActionFlag = 2;
							//SubOption = false;
							break;
						}
					}
				}
			}
			//}
			if (deviceValue == 33) { // 背景音樂
				// 選曲
				//SubOption = true;
				//if (SubOption) {
				String[] music = { "上一首", "*SA8", "上一曲", "*SA8", "上一取",
						"*SA8", "上一娶", "*SA8", "上一手", "*SA8", "上一守",
						"*SA8", "下一首", "*SA9", "下一曲", "*SA9", "下一取",
						"*SA9", "下一娶", "*SA9", "下一手", "*SA9", "下一守", "*SA9" };
				for (int i = 0; i < music.length; i += 2) {
					if (networds.contains(music[i])) {// 有识别词
						iPos = networds.indexOf(music[i]);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + "已设定" + music[i];
							deviceCmd = music[i + 1] + deviceProductCode
									+ "00" + devieID + "00";
							sendMssageAF(modelflag, deviceCmd);
							SubOption = false;
							ActionFlag = 1;
							break;
						}
					}
				}
				//}
				if (SubOption && (timeVal == 0)) {
					timeVal = timeComprartion(1, 0, CheckAct);
					if (timeVal > 0 && timeVal <= 100) {
						string_sw_prams = toHex(timeVal);
						String[] song = { "首", "曲", "取", "娶", "手" };
						for (String str: song) {
							iPos = networds.indexOf(str);
							if (iPos < iVqonPos && iPos != -1) {
								ActionFlag = 1;
								break;
							}
						}
						if (ActionFlag == 1) {
							ReturnAct = ReturnAct + "已设定第"  + timeVal + "首";
							deviceCmd = "*SA8" + deviceProductCode + "00"
									+ devieID + string_sw_prams;
							sendMssageAF(modelflag, deviceCmd);
						} else {
							ReturnAct = ReturnAct + "已设定音量"  + timeVal ;
							deviceCmd = "*SA2" + deviceProductCode + "00"
									+ devieID + string_sw_prams;
							sendMssageAF(modelflag, deviceCmd);
							ActionFlag = 1;
						}
					}
				}
			}
		} else if (deviceValue == 30) { // 調光
			if (MainOption && (timeVal == 0)) {
				timeVal = timeComprartion(1, 0, CheckAct);
				if ((timeVal > 0) && (timeVal <= 100)) {
					string_sw_prams = toHex(timeVal);
					if (networds.contains("饱和度")) {
						ReturnAct = ReturnAct + "已设定饱和度"  + timeVal ;
						deviceCmd = "*S9" + deviceIO + deviceProductCode + "00"
								+ devieID + string_sw_prams;
					} else if (networds.contains("色温")) {
						ReturnAct = ReturnAct + "已设定色温"  + timeVal ;
						deviceCmd = "*SC" + deviceIO + deviceProductCode + "00"
								+ devieID + string_sw_prams;
					} else {
						ReturnAct = ReturnAct + "已设定亮度"  + timeVal ;
						deviceCmd = "*S7" + deviceIO + deviceProductCode + "00"
								+ devieID + string_sw_prams;
					}
					sendMssageAF(modelflag, deviceCmd);
					ActionFlag = 1;
				}
			}
		}
		else if(deviceValue==18){//新風系統
			SubOption = true;
			if (SubOption) {
				//1804
				String[] airfan = { "风量切换", "00", "风量高速", "04", "高速", "04",
						"风量中速", "03", "中速", "03", "风量低速", "02", "低速", "02" };
//				String[] airfan = (String[]) MainActivity.activity.getResources()
//						.getStringArray(R.array.airfan);
				for (int i = 0; i < airfan.length; i += 2) {
					if (networds.indexOf(airfan[i]) != -1) {// 有识别词
						iPos = networds.indexOf(airfan[i]);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + "已" + airfan[i];
							string_sw_prams = airfan[i + 1];
							deviceCmd = "*SA5" + deviceProductCode + "00"
									+ devieID + string_sw_prams;
							sendMssageAF(modelflag, deviceCmd);
							ActionFlag = 1;
							SubOption = false;
							break;
						}
					}
				}
			}
			// airOne
			if (SubOption) {
				//1804
				String[] airOne = { "温度加一", "*SA2", "温度高一点", "*SA2", "温度高点",
						"*SA2", "高一点", "*SA2", "升一点", "*SA2", "调高一点", "*SA2",
						"温度上升", "*SA2", "上升", "*SA2", "再高一点", "*SA2", "温度减一",
						"*SA3", "温度低一点", "*SA3", "温度低点", "*SA3", "低一点", "*SA3",
						"降一点", "*SA3", "第一点", "*SA3", "调低一点", "*SA3", "温度下降",
						"*SA3", "下降", "*SA3", "再低一点", "*SA3" };
//				String[] airOne = (String[]) MainActivity.activity.getResources()
//						.getStringArray(R.array.airOne);
				for (int i = 0; i < airOne.length; i += 2) {
					if (networds.indexOf(airOne[i]) != -1) {// 有识别词
						iPos = networds.indexOf(airOne[i]);
						if (iPos < iVqonPos) {
							ReturnAct = ReturnAct + MainActivity.activity.getString(R.string.alredy)+ airOne[i];
							deviceCmd = airOne[i + 1] + deviceProductCode
									+ "00" + devieID + "00";
							sendMssageAF(modelflag, deviceCmd);
							ActionFlag = 1;
							SubOption = false;
							break;
						}
					}
				}
			}
			if (SubOption && (timeVal == 0)) { // 温度
				timeVal = timeComprartion(1, 0, CheckAct);
				if (timeVal > 0) {
					if (timeVal < 6) {
						if (SubOption) {
							//1804
							String[] AddSub = { "加", "*SA9", "升", "*SA9", "生",
									"*SA9", "昇", "*SA9", "减", "*SAA", "降",
									"*SAA", "将", "*SAA" };
//							String[] AddSub = (String[]) MainActivity.activity.getResources()
//									.getStringArray(R.array.AddSub);
							for (int i = 0; i < AddSub.length; i += 2) {
								if (networds.indexOf(AddSub[i]) != -1) {// 有识别词
									string_sw_prams = toHex(timeVal);
									deviceCmd = AddSub[i + 1]
											+ deviceProductCode + "00"
											+ devieID + string_sw_prams;
									sendMssageAF(modelflag, deviceCmd);
									ActionFlag = 1;
									SubOption = false;
									break;
								}
							}
						}
					} else if (timeVal < 100) {// Set temp
						string_sw_prams = toHex(timeVal);
						deviceCmd = "*SA2" + deviceProductCode + "00" + devieID
								+ string_sw_prams;
						sendMssageAF(modelflag, deviceCmd);
						ActionFlag = 1;
					}
				}
			}
		}

		if (SubOption) {
			String[] SwType = { "副控", "互控" };
			for (String str:SwType) {
				iPos = networds.indexOf(str);
				if (iPos < iVqonPos && iPos != -1) {
					action = "*S0" + deviceIO;
					string_sw_prams = "00";
					deviceCmd = action + deviceProductCode + "00" + devieID
							+ string_sw_prams;
					sendMssageAF(modelflag, deviceCmd);
					ActionFlag = 2;
				}
			}
		}
		// ExtFlag4

		if (ActionFlag >0) {
			//if(MultiFlag==1) {
			//	memDeviceName = words_ls;
			//}
			bSearchFlag++;
			MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
			if (ActionFlag ==1) {
				if ((modelflag != 1) && (!onlyPlaySound)) {
					if ((ProjectUtils.getRootPath().getIsSpeech() == 0) && (!MainActivity.musicPlaySt) && (!MainActivity.musicTTsSt)) {
						String checkstr = deviceCmd.substring(4, 10) + devieMid1
								+ devieMid2 + deviceIO;
						map.put(checkstr, ReturnAct);
					}
				}
			}
		}
	}

	private static boolean checkPeriod(String startTime, String endTime) {

		boolean timeOk = true;
		String str = dateToString(new Date(System.currentTimeMillis()), "HH:mm");
		int NowTime = Integer.parseInt(str.replace(":", ""));
		int decStart = Integer.parseInt(startTime.replace(":", ""));
		int decEnd = Integer.parseInt(endTime.replace(":", ""));
		if (decStart != decEnd) {
			timeOk = ((NowTime >= decStart) && (NowTime <= decEnd));
			if (decStart > decEnd) {
				timeOk = !timeOk;
			}
		}
		return timeOk;
	}

	private void checkPeriodForDeviceModel(Device device, int modelflag,
										   String str_zl) {
		if (checkPeriod(device.getStartTime(), device.getEndTime())
				|| (modelflag == 1)) {
			cStartPos = 0;

			if (str_zl.contains(words_ls)) {
				cStartPos = str_zl.indexOf(words_ls);
			}
			// words_ls = "";
			if ("65".equals(deviceProductCode)) {
				// 电视集合频道
				sendTVCmd(device.getDeviceIO());
				MainActivity.playSound(1,
						"好的,主人,已为您切换" + device.getDeviceName());
				bSearchFlag++;
				MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
			} else if ("05".equals(deviceProductCode)) {
				// 獲取紅外線按鍵名稱
				String KeyWord = str_zl
						.substring(cStartPos + words_ls.length());
				List<RedInfra> list = RedInfraFactory.getInfraById(device
						.getId());
				for (RedInfra infrared : list) {
					boolean pinyingFlag = false;
					String pinying = getPinYin(KeyWord);
					if (KeyWord.contains(infrared.getInfraredName())) {
						pinyingFlag = true;
					} else {
						String pinyingDev = getPinYin(infrared
								.getInfraredName()); // getSelling(scene.getModeName());
						if ((pinying.length() > 0) && (pinyingDev.length() > 0)) {
							if (pinying.equals(pinyingDev)) {
								pinyingFlag = true;
							}
						}
					}
					if (pinyingFlag) {
						bSearchFlag++;
						MainActivity.isAirbus = 30; // MainActivity.isAirbus++;
						MainActivity.playSound(2, "好的,主人,已为您发射" + str_zl);
						ActionFlag = 1;
						sendModeForInfrared(modelflag, infrared, 0);
					}
				}
				if (ActionFlag == 0) {
					initDevie(str_zl, modelflag);
				}
			} else {
				// words_ls = device.getDeviceName();
				// dataLens=words_ls length);
				// ReturnAct = ReturnAct + device.getDeviceName(); // words_ls;
				ReturnAct = device.getDeviceName();
				initDevie(str_zl, modelflag);
			}
		}
	}

	private void sendModeForInfrared(int modelflag, RedInfra infrared,
									 int SendType) {
		String infraredID = infrared.getDeviceId();
		String Id = infraredID.substring(0, 2);
		String mid1 = infraredID.substring(2, 4);
		String mid2 = infraredID.substring(infraredID.length() - 2);
		// if (infrared.getInfrared_sendMode() == 1) {
		if (SendType == 0) {
			String key = toHex(infrared.getInfraredKey() + 1);
			String cmd = "*C0019FA05" + Id + mid1 + mid2 + "A0" + key +"0000";
			// TcpSender.sendMssageAF(cmd);
			sendMssageAF(modelflag, cmd);
		} else {
			String key = toHex(infrared.getInfraredKey() + 128);
			String cmd ;
			String infraCode = infrared.getInfraredCode();
			Boolean Issend = false;
			int i = 0;
			while (true) {

				if (infraCode.length() > 26) {
					Issend = true;
					cmd = "*I00" + key + toHex(i) + "0D"
							+ infraCode.substring(0, 26);
					TcpSender.sendMssageAF(1,cmd);
					infraCode = infraCode.substring(26);
				} else {
					Integer Len = infraCode.length() / 2;
					String IsZero = "00000000000000000000000000";
					cmd = "*I00" + key + toHex(i) + toHex(Len) + infraCode
							+ IsZero.substring(Len * 2);
					TcpSender.sendMssageAF(1,cmd);
					break;
				}
				i++;
			}
			if (Issend) {
				if (SendType == 1) { // send
					cmd = "*I00" + key + "FF0005" + Id + mid1 + mid2 + toHex(i)
							+ "0000000000000000";
				} else { // write
					cmd = "*I00" + key + "FF0105" + Id + mid1 + mid2 + toHex(i)
							+ "0000000000000000";
				}
				TcpSender.sendMssageAF(1,cmd);
			}
		}

	}

	private String GettimePara(String str) {

		String[] time = { "小", "时", "分", "秒", "点", ":" };
		String[] number = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "两", "拾",
				"十", "百" };
		int ContValue = 0;
		int hh = 0;
		int mm = 0;

		int sec = 0;
		String UnitStr;
		String PreUnitStr = "";
		boolean bFlag = true;
		int bFirstOk = 0;
		int MemAdd = 0;
		int k;
		int j;
		// boolean bFlag = false;
		for (j = 0; j < str.length(); j++) {
			UnitStr = str.substring(j, j + 1);
			for (k = 0; k < number.length; k++) {
				if (UnitStr.equals(number[k])) {
					break;
				}
			}
			if (k < number.length) { //
				if (!bFlag) {
					ContValue = 0;
				}
				if ((k == 21) || (k == 22)) //  Æ
				{
					if (ContValue == 0) {
						ContValue = 1;
					}
					MemAdd = 1;
				} else if (k == 23) // ∞Ÿ
				{
					ContValue = (ContValue * 10);
					MemAdd = 1;
				} else {
					if (k == 20) {
						k = 2;
					} else if (k > 9) {
						k -= 10;
					}
					ContValue = (ContValue * 10) + k;
					MemAdd = 0;
				}
				bFlag = true;
			} else {
				if (bFlag) {
					if (MemAdd == 1) {
						MemAdd = 0;
						ContValue = (ContValue * 10);
					}
					int n = 0;
					for (; n < time.length; n++) {
						if (UnitStr.equals(time[n])) {
							break;
						}
					}
					if (n < time.length) {
						switch (n) {
							case 0:// "小"
								bFlag = true;
								break;
							case 1:// "时"
								hh = ContValue;
								bFlag = false;
								bFirstOk = 1;
								ReturnAct = ReturnAct + hh + "小" + time[n];
								break;
							case 2:// "分"
								mm = ContValue;
								bFirstOk = 1;
								ReturnAct = ReturnAct + mm + time[n] + "钟";
								break;
							case 3:// "秒"
								sec = ContValue;
								bFirstOk = 1;
								ReturnAct = ReturnAct + sec + time[n] + "钟";
								break;
							case 4:// "点"
							case 5:// ":"
								hh = ContValue;
								bFlag = false;
								bFirstOk = 2;
								ReturnAct = ReturnAct + hh + "点";
								break;
						}
						PreUnitStr = UnitStr;
					} else {
						if (bFirstOk > 0) {
							if (PreUnitStr.equals(":")) {
								mm = ContValue;
								ReturnAct = ReturnAct + mm + "分";
							}
							break;
						}
					}
				} else {
					if (bFirstOk > 0) {
						if (UnitStr.equals("半") && PreUnitStr.equals("点")) {
							mm = 30;
							ReturnAct = ReturnAct + "半";
						}
						break;
					}
					ContValue = 0;
				}
			}
		}
		if (bFirstOk == 2) {
			String TimeFormat[] = { "早上", "下午", "晚上" };
			for (k = 0; k < TimeFormat.length; k++) {
				if (str.contains(TimeFormat[k])) {
					break;
				}
			}
			if (k < TimeFormat.length) {
				ReturnAct = TimeFormat[k] + ReturnAct;
				if ((k > 0) && (hh < 12)) {
					hh = hh + 12;
				}
			}
		}
		return (bFirstOk + ":" + (hh < 10 ? ("0" + hh) : hh) + ":"
				+ (mm < 10 ? ("0" + mm) : mm) + ":"
				+ (sec < 10 ? ("0" + sec) : sec) + ":" + j);
	}

	private int timeComprartion(int select, int iPos, String str) {

		String[] time = { "秒", "分", "时", ";" };
		int ContValue = 0;
		int LimitPos = 0;
		String UnitStr = "";
		boolean bFlag = true;
		boolean bFirstOk = false;
		timeReturn="";
		if (select == 0) {// Time
			bFlag = false;
			for (int i = iPos; i < str.length(); i++) {
				for (int n = 0; n < time.length; n++) {
					if (str.substring(i, i + 1).equals(time[n])) {
						if ((n < 2) || ((n == 2) && (UnitStr.equals("小")))
								|| (n == 3)) {
							LimitPos = n;
							if (n < 3) {
								bFlag = true;
							}
							break;
						}
					}
					if ((bFlag) || (LimitPos == 3)) {
						break;
					}
				}
				UnitStr = str.substring(i, i + 1);
			}
		} else if (select == 2) {// "点"
			bFlag = false;
			if (str.contains("点")) {
				UnitStr = "点";
				bFlag = true;
			}
		} else if (select == 3) {// "分"
			bFlag = false;
			if (str.contains("分")) {
				UnitStr = "分";
				bFlag = true;
			}
		}
		String[] number = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "壹", "两",
				"拾", "十", "百", ";" };
		if (bFlag) {
			int MemAdd = 0, k;
			int j;
			bFlag = false;
			for (j = iPos; j < str.length(); j++) {
				for (k = 0; k < number.length; k++) {
					if (str.substring(j, j + 1).equals(number[k])) {
						break;
					}
				}
				if (k < number.length) //
				{
					if (k == 25) {
						break;
					} else {
						if (bFirstOk) {
							bFirstOk = false;
							ContValue = 0;
						}
						if ((k == 22) || (k == 23)) //  Æ
						{
							if (ContValue == 0) {
								ContValue = 1;
							}
							MemAdd = 1;
						} else if (k == 24) // ∞Ÿ
						{
							ContValue = (ContValue * 10);
							MemAdd = 1;
						} else {
							if (k == 20) {
								k = 1;
							} else if (k == 21) {
								k = 2;
							} else if (k > 9) {
								k -= 10;
							}
							ContValue = (ContValue * 10) + k;
							MemAdd = 0;
						}
						bFlag = true;
					}
				} else {
					if (bFlag) {
						if (str.substring(j, j + 1).equals(UnitStr)) {
							break;
						} else {
							if (MemAdd == 1) {
								MemAdd = 0;
								ContValue = (ContValue * 10);
							}
							bFirstOk = true; // break;
						}
					}
				}
			}
			if (MemAdd == 1) {
				ContValue = (ContValue * 10);
			}
			if (ContValue > 0) {
				UnitStr = ",已设定 " + ContValue;
				if (select == 0) {
					switch (LimitPos) {
						case 0: // √Î
							if (ContValue > 63) {
								ContValue = 63;
							}
							UnitStr = UnitStr + "秒钟";
							break;
						case 1: // ∑÷
							if (ContValue > 60) {
								ContValue = 60;
							}
							ContValue = ContValue + 64;
							UnitStr = UnitStr + "分钟";
							break;
						case 2: // ïr
							if (ContValue > 12) {
								ContValue = 12;
							}
							ContValue = ContValue + 128;
							UnitStr = UnitStr + "小时";
							break;
					}
				}
				//ReturnAct = ReturnAct + UnitStr;
				timeReturn=UnitStr;
			}
		}
		return ContValue;
	}

	private static List<String> _GetCmdArr = new ArrayList<>();

	private void GetDeviceState() {
		String sendCmd;
		deviceValue = Integer.parseInt(deviceProductCode, 16);
		sendCmd = "*C0009FA" + deviceProductCode + devieID+ devieMid1 + devieMid2 + "00000000" ;

		boolean isUnExit = true;
		if (_GetCmdArr.size() > 0) {
			for (String str : _GetCmdArr) {
				if (str.equals(sendCmd)) {
					isUnExit = false;
					break;
				}
			}
		}

		if (isUnExit) {
			_GetCmdArr.add(sendCmd);
			TcpSender.sendMssageAF(0,sendCmd);
		}
	}

	private void sendMssageAF(int modeEdit, String str) {
		/*
		String sendCmd;
		// String cType;
		// String cdid;
		String cAct;
		String cPara;
		if (modeEdit == 1) {
			String device = "";
			if (str.substring(0, 2).equals("*S")) {
				device = str.substring(4, 6) + str.substring(8, 10)
						+ str.substring(2, 4) + str.substring(10, 12);
			} else if (str.substring(0, 6).equals("*C0019")) {
				device = str.substring(8, 10) + str.substring(12, 14)
						+ str.substring(16, 18);
			} else if (str.substring(0, 6).equals("*C0032")) {
				device = str.substring(8, 10) + str.substring(12, 14) + "F"
						+ str.substring(17, 18) + str.substring(14, 16);
			}
			sendCmd = "*M81" + modecode + modetime + modeIo + devieMid1
					+ devieMid2 + device + modeSthh + modeStmm + modeEndhh
					+ modeEndmm;
			//isSendMode = true;
		} else {
			sendCmd = str;
			String cCmdType = str.substring(0, 2);
			if (cCmdType.equals("*S")) {
				// cType = str.substring(4, 6);
				// cdid = str.substring(8, 10);
				cAct = str.substring(2, 4);
				cPara = str.substring(10, 12);
				// sendCmd = "*C0019AA" + deviceProductCode + "00" + devieID
				// + "AA" + cAct + cPara + devieMid1 + devieMid2;
				sendCmd = "*C0019" + SendType + deviceProductCode + "00"
						+ devieID + "AA" + cAct + cPara + devieMid1 + devieMid2;
			}
		}
		TcpSender.sendMssageAF(0,sendCmd);
		*/
		String sendCmd;
		String cType;
		String cdid;
		String cAct;
		String cPara;
		if (modeEdit == 1) {
			String device = "";
			if (str.substring(0, 2).equals("*S")) {
				device = str.substring(4, 6) + str.substring(8, 10)+ devieMid1
						+ devieMid2 + str.substring(2, 4) + str.substring(10, 12);
			} else if (str.substring(0, 6).equals("*C0019")) {
				//*C0019FA0100IDAA(act)(para)(mid)(mid)     OLD
				//*C0019FA01(ID)(MID)(MID)(ACT)(PARA)...    NEW
				device = str.substring(8, 12)+ devieMid1 + devieMid2 + str.substring(16, 20);
			} else if (str.substring(0, 6).equals("*C0032")) {
				device = str.substring(8, 10) + str.substring(12, 14) + "F"
						+ str.substring(17, 18) + str.substring(14, 16);
			}
			sendCmd = "*M81" + modecode + modetime + modeIo  + device  + modeSthh + modeStmm + modeEndhh
					+ modeEndmm + modeMonth;
			/*
			isSendMode = true;
			if(ModeGateMac.length()>0) {
				sendToCurrtneGaway(ModeGateType,ModeGateMac,sendCmd);
				return;
			}
			*/
		} else if ((modeEdit == 2) || (modeEdit == 3)) {
			String device = "";
			if (str.substring(0, 2).equals("*S")) {
				device = str.substring(4, 6) + str.substring(8, 10)+ devieMid1
						+ devieMid2 + str.substring(2, 4) + str.substring(10, 12);
			} else if (str.substring(0, 6).equals("*C0019")) {
				device = str.substring(8, 12)+ devieMid1 + devieMid2 + str.substring(16, 20);
			} else if (str.substring(0, 6).equals("*C0032")) {
				device = str.substring(8, 10) + str.substring(12, 14) + "F"
						+ str.substring(17, 18) + str.substring(14, 16);
			}
			sendCmd = "*I" +modeMonth+ toHex(randomKey) + "FF" + modeIo + "248" + (modeEdit - 1)
					+ device+ modeSthh + modeStmm + modeEndhh + modeEndmm + modetime;
			randomKey++;
			if (randomKey >= 256) {
				randomKey = 0;
			}
			return;
		} else if (modeEdit == 4) {
			cAct = str.substring(2, 4);
			cPara = str.substring(10, 12);
			if (cPara.equals("40")) {
				sendCmd = "*C0019FA" + deviceProductCode + devieID + devieMid1 + devieMid2+ "E0" + cPara + "0000";
			} else {
				int IrCode = Integer.parseInt(cPara, 16);
				cPara = toHex(IrCode + 1);
				sendCmd = "*C0019FA05" + devieID + devieMid1+ devieMid2 + "E0" + cPara +"0000";
			}
		} else {
			sendCmd = str;
			String cCmdType = str.substring(0, 2);
			if (cCmdType.equals("*S")) {
				cAct = str.substring(2, 4);
				cPara = str.substring(10, 12);
				sendCmd = "*C0019FA" + deviceProductCode + devieID + devieMid1 + devieMid2
						+ cAct + cPara + "00" +allControl;
			}
		}
		TcpSender.sendMssageAF(0,sendCmd);
		/*
		List<GateWay> gateWayList = GateWayService.list;
		for (int i = 0; i < gateWayList.size(); i++) {
			GateWay gateway = gateWayList.get(i);
			if (gateway.getIsCurrent() ==1) {
				history.setHistoryName(ReturnAct.replace("已", ""));
				history.setHistoryCode(sendCmd);
				history.setMasterMac(gateway.getGatewayID());
				MainActivity.getInstance().sendHistory();
			}
		}
		*/
	}

	private String format(String s) {
		String str = s.replaceAll(
				"[`~!$%^&()=|{}'',\\[\\).<>~！￥%……& amp（）——|{}【】‘”“’。，、？|]",
				"");
		return str;
	}

	private static String toHex(int number) {
		return (((number <= 15) ? "0" : "") + Integer.toHexString(number)
				.toUpperCase());
	}

	public boolean PinYinComparison(String source1, String source2) {
		boolean result = false;
		String pinyingDev = getPinYin(source2); // getSelling(CampStr);
		if ((!source1.equals("") && (source1.length() > 0))) {
			if ((!pinyingDev.equals("") && (pinyingDev.length() > 0))) {
				if (source1.contains(pinyingDev)) {
					result = true;
				}
			}
		}
		return result;
	}

	public static String getPinYin(String hanzi) {
		ArrayList<Token> tokens = HanziToPinyin.getInstance().get(hanzi);
		StringBuilder sb = new StringBuilder();
		if (tokens != null && tokens.size() > 0) {
			for (Token token : tokens) {
				if (Token.PINYIN == token.type) {
					sb.append(token.target);
				} else {
					sb.append(token.source);
				}
			}
		}
		return sb.toString().toUpperCase();
	}

	public static void blackCode(String _blackCode) {
		try {
			String blacCode = _blackCode;
			String cmdtype = blacCode.substring(0, 2);
			if (cmdtype.equals("*d") || cmdtype.equals("*c")
					|| cmdtype.equals("*a") || cmdtype.equals("*T")
					|| cmdtype.equals("*t")) {
				if (blacCode.substring(4, 6).equals("07")) {
					Message msg = handler.obtainMessage();
					msg.what = 1;
					msg.obj = blacCode;
					handler.sendMessage(msg);
				} else {
					Message msg = handler.obtainMessage();
					msg.what = 0;
					msg.obj = blacCode;
					handler.sendMessage(msg);
				}
			} else {
				if (cmdtype.equals("*C")) {
					// *C0032AAFF00FF0100000000
					String CommandType = blacCode.substring(4, 6);
					if ("32".equals(CommandType)) { // 情景指令
						Message msg = handler.obtainMessage();
						msg.what = 2;
						msg.obj = blacCode;
						handler.sendMessage(msg);
					}
				}
			}
		} catch (Exception e) {

		}
	}

	public static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
				String datastr = msg.obj.toString();
				if (msg.what == 0) {

					String startCmd = datastr.substring(4, 8);
					String deviceID = datastr.substring(8, 14);

					List<Device> list = DeviceFactory.getDevices(deviceID);
					for (int i = 0; i < list.size(); i++) {
						Device device = list.get(i);
						String cmd = startCmd + deviceID + device.getDeviceIO();
						if (!map.isEmpty()) {
							String retback = map.get(cmd);
							if (retback != null) {
								if((!MainActivity.musicPlaySt) && (!MainActivity.musicTTsSt)){
									MainActivity.playSound(4, retback);
								}
								map.remove(cmd);
								Log.e("out", cmd + retback);
							}
						}
					}

				} else if (msg.what == 1) {
					int Id = Integer.valueOf(datastr.substring(8, 10), 16);
					if (Id < 28) {
						String str = AnHongUitils.getAnHong(Id);
						int state = Integer.valueOf(datastr.substring(18, 20),
								16);
						if (((state & 0xf0) > 0) && ((state & 2) > 0)) {
							String deviceID = datastr.substring(8, 14);
							str = DeviceFactory.getName(deviceID) + str;
							MainActivity.activity.addAnHong(str + "["
									+ deviceID + "]");
							MainActivity.playSound(5, str);
						}
					}
				} else if (msg.what == 2) {
					// *C2732AAFF00FF0400000200
					int modelCode = Integer.valueOf(datastr.substring(14, 16),
							16);
					int modeLoop = Integer.valueOf(datastr.substring(16, 18),
							16);
					List<Mode> sceneArray = ModeFactory.getAll();
					for (int index = 0; index < sceneArray.size(); index++) {
						Mode scene = sceneArray.get(index);
						if ("FF".equals(scene.getModeType())) {
							if ((modelCode == scene.getModeCode())
									&& (modeLoop == scene.getModeLoop())) {// 场景代码
								// joe 2017_08_28
								if (checkPeriod(scene.getStartTime(),
										scene.getEndTime())) {
									String nickName = scene.getModeNickName();
									String upString = "";
									int startPos = nickName.indexOf("[");
									int endPos = nickName.indexOf("]");
									if ((startPos != -1) && (endPos != -1)
											&& (endPos > startPos)) {
										upString = nickName.substring(
												startPos + 1, endPos);
										if (upString.length() > 0) {
											//MainActivity.UploadText(upString,1);
											SendCMD.getInstance().DecodeinfoAction(upString,1,1);
										}
									}
								}
							}
						}
					}
				}
			}
			//
			catch (Exception e) {
			}
		}
	};

	private static IWidgetDAO Sqlite() {
		return MyApplication.getInstance().getWidgetDataBase();
	}

	// date类型转换为String类型
	// formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
	// data Date类型的时间
	private static String dateToString(Date data, String formatType) {
		return new SimpleDateFormat(formatType).format(data);
	}

	// long类型转换为String类型
	// currentTime要转换的long类型的时间
	// formatType要转换的string类型的时间格式
	private String longToString(long currentTime, String formatType) {
		Date date = longToDate(currentTime, formatType); // long类型转成Date类型
		//	String strTime = dateToString(date, formatType); // date类型转成String
		return dateToString(date, formatType); // date类型转成String
	}

	// string类型转换为date类型
	// strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
	// HH时mm分ss秒，
	// strTime的时间格式必须要与formatType的时间格式相同
	private Date stringToDate(String strTime, String formatType) {
		SimpleDateFormat formatter = new SimpleDateFormat(formatType);
		Date date = null;
		try {
			date = formatter.parse(strTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

	// long转换为Date类型
	// currentTime要转换的long类型的时间
	// formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
	private Date longToDate(long currentTime, String formatType) {
		Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
		String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
		//Date date = stringToDate(sDateTime, formatType);
		return stringToDate(sDateTime, formatType);
	}

	// String类型转换为long类型
	// strTime要转换的String类型的时间
	// formatType时间格式
	// strTime的时间格式和formatType的时间格式必须相同
	private long stringToLong(String strTime, String formatType) {
		Date date = stringToDate(strTime, formatType); // String类型转成date类型
		if (date == null) {
			return 0;
		} else {
			//long currentTime = dateToLong(date); // date类型转成long类型
			return dateToLong(date); // date类型转成long类型
		}
	}

	// date类型转换为long类型
	// date要转换的date类型的时间
	private long dateToLong(Date date) {
		return date.getTime();
	}

	private static String getWebsiteDatetime(String webUrl) {
		try {
			URL url = new URL(webUrl);// 取得资源对象
			URLConnection uc = url.openConnection();// 生成连接对象
			uc.connect();// 发出连接
			long ld = uc.getDate();// 读取网站日期时间
			Date date = new Date(ld);// 转换为标准时间对象
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
					Locale.CHINA);// 输出北京时间
			return sdf.format(date);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm");
	 * GregorianCalendar gc=new GregorianCalendar(); gc.setTime(new
	 * java.util.Date()); gc.add(6,1);
	 * //System.out.println("昨天的日期："+df.format(gc.getTime()));
	 * setCode("昨天的日期："+df.format(gc.getTime()));
	 *
	 * String sk =SendCMD.getPinYin("客廳,客厅"); setCode(sk);
	 */
	private static int getCharCount(String str, String charStr) {
		int count = 0;
		for (int i = 0; i <= str.length() - 1; i++) {
			String getstr = str.substring(i, i + 1);
			if (getstr.equals(charStr)) {
				count++;
			}
		}
		return count;
	}
	private void CheckTouYingjiDevice(String action ,int modelflag){
		if(modelflag==0){
			String timerOrder = deviceModelParam.getDeviceOrdered();
			try {
				BindProject bindProject = JSONHelper.parseObject(timerOrder, BindProject.class);
				if(bindProject!=null) {
					SubControlWords = bindProject.getTent() + action;
					delaySubControl = 1;
				}
			}catch(Exception e){

			}
		}
	}
}
